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?
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.
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()) .
Try
> sum(v > 2 & v < 5)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With