Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 831
Daniel Standage Avatar asked Sep 29 '10 01:09

Daniel Standage


People also ask

How do I check if a value is in a range in R?

Check if a numeric value falls between a range in R Programming – between() function. between() function in R Language is used to check that whether a numeric value falls in a specific range or not. A lower bound and an upper bound is specified and checked if the value falls in it.

How do I count the number of observations in a group in R?

count() lets you quickly count the unique values of one or more variables: df %>% count(a, b) is roughly equivalent to df %>% group_by(a, b) %>% summarise(n = n()) .


2 Answers

Try

> sum(v > 2 & v < 5) 
like image 135
stevendesu Avatar answered Sep 25 '22 06:09

stevendesu


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.

like image 33
Greg Snow Avatar answered Sep 26 '22 06:09

Greg Snow