2

I'm still having problems calculating numbers.

Trying to find the amount of numbers inside [-0.5 , 0.5] the first line, and the amount of numbers outside the same range in the second line.

I use abc = rnorm(100, mean=0, sd=1). So I have 100 numbers in total, but i only have 35 numbers inside the range, and 35 outside the range, that dosen't add up to 100.

length(abc[abc>=-0.5 & abc<=0.5])
[1] 35

length(abc[abc<-0.5 & abc>0.5])
[1] 35

Then I tried:

length(which(abc>=-0.5 & abc<=0.5))
[1] 40

length(which(abc<-0.5 & abc>0.5))
[1] 26

And it still doesn't add up to 100. What's wrong?

4

4 回答 4

10

你在追求:

R> set.seed(1)
R> abc = rnorm(100, mean=0, sd=1)
R> length(abc[abc >= -0.5 & abc <= 0.5])
[1] 41
R> length(abc[abc < -0.5 | abc > 0.5])
[1] 59

什么地方出了错

两件事情:

  1. abc < -0.5 & abc > 0.5要求小于 -0.5大于 0.5的值
  2. 但是,您实际上有:abc[abc<-0.5 & abc>0.5]由于范围界定,这会有所不同。让我们把它分开:

    R> abc[abc<-0.5 & abc>0.5]
     [1] 1.5953 0.7383 0.5758 1.5118 1.1249 0.9438 <snip>
    

    现在让我们看看abc

    R> abc
    [1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  
    

    你改变了abc! 这是因为<-是赋值运算符。您已设置abc0.5 & abc > 0.5。为避免这种情况,请使用间距(如我的代码中所示)。

于 2013-04-18T08:01:10.997 回答
3

当想要像这样在半径内外查找数字时,考虑绝对值会很有帮助,然后您只需进行一次比较:

length(abc[abs(abc)<=0.5])
[1] 41
length(abc[abs(abc)>0.5])
[1] 59

或者您可以在一行中使用cutand来完成:table

table(cut(abs(abc),c(-Inf,0.5,Inf)))

  (-Inf,0.5] (0.5,Inf] 
       41        59 
于 2013-04-18T08:14:06.030 回答
2

作为捷径,您也可以这样做:

set.seed(1)
abc <- rnorm(100, mean=0, sd=1)
sum(abc>=-0.5 & abc<=0.5)
# [1] 41
sum(abc< -0.5 | abc>0.5)
# [1] 59

这是有效的,因为sum将 TRUE 视为 1,将 FALSE 视为 0。

于 2013-04-18T08:03:13.790 回答
0

或者通过subset

set.seed(1)
abc <- rnorm(100, mean=0, sd=1)

length(subset(abc, abc >= (-0.5) & abc <= 0.5))
[1] 41
length(subset(abc, abc < (-0.5) | abc > 0.5))
[1] 59
于 2013-04-18T08:07:24.653 回答