Dear all, I'm looking for a function comparable to switch, to categorize a continuous variable in a few levels. Off course that can be done with a series of ifelse statements, but that looks rather clumsy. I looked at switch, but couldn't figure out how to use it for this. I guess that's not possible, as it only works with characters or integers, not with intervals. Basically, I'm looking for a clean way to do : test <- runif(10,1,100) testFunc <-function(x){ x <- ifelse(test<10,"lowest", ifelse(10<=test & test <50,"low", ifelse(50<=test & test <90,"high", ifelse(90<=test & test<100,"highest",NA) ) ) ) return(as.factor(x)) } testFunc(test) Thank you in advance
Never mind, found the function : cut(test,breaks=c(0,10,50,90,100),labels=c("lowest","low","high","highest"),include.lowest=T,right=F) Cheers Joris On Mon, Nov 23, 2009 at 2:14 PM, joris meys <jorismeys at gmail.com> wrote:> Dear all, > > I'm looking for a function comparable to switch, to categorize a > continuous variable in a few levels. Off course that can be done with > a series of ifelse statements, but that looks rather clumsy. I looked > at switch, but couldn't figure out how to use it for this. I guess > that's not possible, as it only works with characters or integers, not > with intervals. > > Basically, I'm looking for a clean way to do : > test <- runif(10,1,100) > > testFunc <-function(x){ > x <- ?ifelse(test<10,"lowest", > ? ? ? ?ifelse(10<=test & test <50,"low", > ? ? ? ? ?ifelse(50<=test & test <90,"high", > ? ? ? ? ? ?ifelse(90<=test & test<100,"highest",NA) > ? ? ? ? ?) > ? ? ? ?) > ? ? ?) > return(as.factor(x)) > } > > testFunc(test) > > Thank you in advance >
On Nov 23, 2009, at 8:14 AM, joris meys wrote:> Dear all, > > I'm looking for a function comparable to switch, to categorize a > continuous variable in a few levels.?cut> Off course that can be done with > a series of ifelse statements, but that looks rather clumsy. I looked > at switch, but couldn't figure out how to use it for this. I guess > that's not possible, as it only works with characters or integers, not > with intervals. > > Basically, I'm looking for a clean way to do : > test <- runif(10,1,100)> test <- runif(10,1,100) > testcut <- cut(test, breaks=c(-Inf, 10, 50, 90, 100)) > table(testcut) testcut (-Inf,10] (10,50] (50,90] (90,100] 1 4 5 0> > testFunc <-function(x){ > x <- ifelse(test<10,"lowest", > ifelse(10<=test & test <50,"low", > ifelse(50<=test & test <90,"high", > ifelse(90<=test & test<100,"highest",NA) > ) > ) > ) > return(as.factor(x)) > } > > testFunc(test) > > Thank you in advance-- David Winsemius, MD Heritage Laboratories West Hartford, CT