简体   繁体   English

计算R范围内的向量值数量

[英]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. 在R中,如果您在向量而不是标量上测试条件,它将返回一个向量,其中包含向量中每个值的比较结果。 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? 例如,如何确定大于2但小于5的值的数量?

尝试

> sum(v > 2 & v < 5)

There are also the %<% and %<=% comparison operators in the TeachingDemos package which allow you to do this like: TeachingDemos程序包中还有%<%和%<=%比较运算符,您可以通过以下方式进行操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM