views:

88

answers:

3

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?

+4  A: 

Try

> sum(v > 2 & v < 5)
steven_desu
Daniel Standage
steven_desu
R-intro, ch. 9.2.1
aL3xa
Marek
A: 

Use which:

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

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.

Greg Snow
That is definitely helpful. I tried something like that but got syntax errors. That's how I would write in on paper or LaTeX, so it's good to know. By the way, I assume you meant x %<=% 5 and not x %<= 5%.
Daniel Standage
Thanks for catching the % that tried to float away, I fixed it now.
Greg Snow