开发者

Count number of vector values in range with R

In R, if you test a condition on a vector instead of a scalar, it will return a vector containing the result of the comparison for each value in the vector. For example...

> v <- c(1,2,3,4,5)
> v > 2
[1] FALSE FALSE  TRUE  TRUE  TRUE

In this way, I can determine the number of elements in a vector that are above or below a certain number, like so.

> sum(v > 2)
[1] 3
> sum(v < 2)
[1] 1

Does anyone know how I can determine the number of values in a given range? For example, how would I determine the number of values greater than 2 but less th开发者_运维百科an 5?


Try

> sum(v > 2 & v < 5)


There are also the %<% and %<=% comparison operators in the TeachingDemos package which allow you to do this like:

sum( 2 %<% x %<% 5 )
sum( 2 %<=% x %<=% 5 )

which gives the same results as:

sum( 2 < x & x < 5 )
sum( 2 <= x & x <= 5 )

Which is better is probably more a matter of personal preference.


Use which:

 set.seed(1)
 x <- sample(10, 50, replace = TRUE)
 length(which(x > 3 & x < 5))
 # [1]  6
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜