Count number of vector values in range with R

走远了吗. 提交于 2019-12-20 16:16:36

问题


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 than 5?


回答1:


Try

> sum(v > 2 & v < 5)



回答2:


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.




回答3:


Use which:

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


来源:https://stackoverflow.com/questions/3818147/count-number-of-vector-values-in-range-with-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!