I have a vector with numbers that looks like this: c(52.2,76.3,16.1,85.8). I would like to determine in which interval in seq(15,90,5) each of the values lie and make a new vector with numbers that indicate the specific interval/category.
The following function works, but looks rather cumbersome so hopefully someone can help me to make this more efficient/concise.
testfun <- function(x){
ifelse(x>=15 & x<20, 1, ifelse(x>=20 & x<25, 2, ifelse(x>=25 & x<30, 3,
ifelse(x>=30 & x<35, 4, ifelse(x>=35 & x<40, 5, ifelse(x>=40 & x<45, 6,
ifelse(x>=45 & x<50, 7, ifelse(x>=50 & x<55, 8, ifelse(x>=55 & x<60, 9,
ifelse(x>=60 & x<65, 10, ifelse(x>=65 & x<70, 11, ifelse(x>=70 & x<75, 12,
ifelse(x>=75 & x<80, 13, ifelse(x>=80 & x<85, 14, ifelse(x>=85 & x<90, 15,
ifelse(x>=85 & x<90, 16, NA))))))))))))))))}
> testfun(c(52.2,76.3,16.1,85.8))
[1] 8 13 1 15
Many thanks!
Ps. Feel free to edit this question / title
Use cut and assign labels:
x <- c(52.2,76.3,16.1,85.8 , 90 )
cut( x , breaks = seq(15,90,5) , labels = c(1:15) , include.lowest = TRUE )
#[1] 8 13 1 15
#Levels: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
You can use `cut` for example
as.numeric(cut(c(52.2,76.3,16.1,85.8), breaks = seq(15,90,5)))
[1] 8 13 1 15
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