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