Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple function counting values from a list within certain range

Tags:

r

I want to create a function that takes 3 arguments: a list of values and two cutoff values (a high and a low). Then I want it to how many of the values in the list are within the range of the two cutoff values.

So far I have tried:

count <- function(y, x1, x2){
  tmp1 <- length(y)
  tmp2 <- length(y>x1)
  tmp3 <- length(tmp2<=x2)
  return(tmp3)
}

and

count <- function(y, x1, x2){
  results <- list()
  for (i in y) {
    if(y > x1 & y <= x2) {
      results <- results+1
    }
  }
  return(results)
}

none of them work. Can some help me correct my code?

like image 822
Mads Obi Avatar asked Apr 30 '15 20:04

Mads Obi


1 Answers

Simplify it down. Take the sum of a vectorized logical operation

f <- function(x, y, z) sum(x > y & x < z)
f(1:10, 3, 7)
# [1] 3

But the data.table authors are one step ahead of you. They've written a function between(). I believe there is also one in the dplyr package as well.

library(data.table)
between
# function (x, lower, upper, incbounds = TRUE) 
# {
#     if (incbounds) 
#         x >= lower & x <= upper
#     else x > lower & x < upper
# }
# <bytecode: 0x44fc790>
# <environment: namespace:data.table>

So for the same result as above you can simply do

sum(between(1:10, 3, 7, FALSE))
# [1] 3
like image 62
Rich Scriven Avatar answered Sep 18 '22 18:09

Rich Scriven