jeudi 24 août 2017

R: Random number between range if value in another vector is between x and y

I have a vector ACCNS in a data.frame E. ACCNS has discrete values 0, 1, 5, 12, 26 or 40. I'd like to make another vector ACCNSrandom that has a 'runif' value based on 0-1, 1-5, 5-12, 12-26, 26-40 and 40-100. I've tried this with a nested ifelse but I get the same value each time (as reported here). I can't work out how to apply the answer given in that post to a more general form. Any help would be much appreciated.

E<-data.frame(ACCNS=sample(c(0,1,2.5,5,12,26,40),50,replace = T))

E$ACCNSrandom <- ifelse( E$ACCNS == 0, runif(1,0,1),
                         ifelse(E$ACCNS>0 & E$ACCNS <= 2.5, runif(1,1,2.5),
                         ifelse( E$ACCNS > 2.5 & E$ACCNS<12, runif(1,2.5,12), 
                                 ifelse( E$ACCNS >= 12 & E$ACCNS<40, runif(1,12,40),  
                                         ifelse( E$ACCNS >= 40 & E$ACCNS<100, runif(1,40,100),0 
                                                  )  )  ) ) )

Aucun commentaire:

Enregistrer un commentaire