Monday 4 December 2017

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

itemprop="text">

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
href="https://stackoverflow.com/questions/31685847/using-ifelse-with-random-variate-generation-in-a-function-applied-to-a-vector">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
) ) ) )
)


class="post-text" itemprop="text">
class="normal">Answer



A simple
vectorized solution:



lower <-
c(0, 1, 2.5, 5, 12, 26, 40)
upper <- c(lower[-1], 100)
E <-
data.frame(ACCNS = sample(lower, 50, replace = TRUE))

ind <-
match(E$ACCNS, lower)
E$ACCNSrandom <- runif(length(ind), lower[ind],
upper[ind])



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...