Count number of vector values in range with R
Solution 1
Try
> sum(v > 2 & v < 5)
Solution 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.
Solution 3
Use which:
set.seed(1)
x <- sample(10, 50, replace = TRUE)
length(which(x > 3 & x < 5))
# [1] 6
Daniel Standage
Husband, father, scholar, scientist, programmer, lapsed musician, flipper of pancakes, baker of biscuits.
Updated on July 18, 2022Comments
-
Daniel Standage almost 2 years
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?