lundi 5 juin 2017

Conditional statements with too many ifelse statements

I have the following data:

my.list<-list(a=c(55,17,18,18,18,21),
b=c(11,17,17,17,22,18,22),
c=c(55,17,22,22,22,22,22,21,30))    

x<-c(1,1,1,1,2,2,3,3,3,3,3,3,3,3,3)    

set.seed(1)    

my.function <- function(x) {

ifelse(x == 1,sample(my.list$a,replace = T),
ifelse(x == 2,sample(my.list$b,replace = T),
ifelse(x == 3,sample(my.list$c,replace = T)


)))    
}        

p<-sapply(x, my.function)    

In the "real" dataset I have much more ifelse-statements than shown above and the code is too long.

Is there a smarter solution so I don't need to write so many ifelse-statements? Every ifelse-statement is related to a unique list as above with different lengths that I draw samples from.

Aucun commentaire:

Enregistrer un commentaire