2

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

Rob
  • 1,460
  • 2
  • 16
  • 23

2 Answers2

6

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
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
4
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
jdharrison
  • 30,085
  • 4
  • 77
  • 89
  • hi @jdharrison, wanted to comment on the comments to your answer on [lapply-ing with the “$” function;](http://stackoverflow.com/questions/18216084) but can't since it's now deleted. I thought it even though it didn't quite answer the OP's actual question, it was a good attempt and didn't deserve the offense that some people gave it. I hope that the offense was in jest, in response to your ;), as people as generally friendly here, but either way, I hope you aren't discouraged and will continue to participate in StackOverflow. – Aaron left Stack Overflow Aug 13 '13 at 19:00
  • lol @Aaron no offense was taken. I would have expanded on my answer but the guys were covering it very well in the comments so felt it best to withdraw the answer so someone could write up a more complete answer. – jdharrison Aug 13 '13 at 19:08