1
votes

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 
                                                  )  )  ) ) )
2
I'm open to any solutions as long as it's a decimal not a factor as I need to multiply it with another number later on.HCAI
You should include this comment in the question, it's part of it.Rui Barradas

2 Answers

2
votes

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])
2
votes

Here's one way of doing what you want.

set.seed(1234)  # make it reproducible

i1 <- E$ACCNS == 0
i2 <- 0 < E$ACCNS & E$ACCNS <= 2.5
i3 <- 2.5 < E$ACCNS & E$ACCNS < 12
i4 <- 12 <= E$ACCNS & E$ACCNS < 40
i5 <-  40 <= E$ACCNS & E$ACCNS < 100

E$ACCNSrandom <- numeric(nrow(E))
E$ACCNSrandom[i1] <- runif(sum(i1), 0, 1)
E$ACCNSrandom[i2] <- runif(sum(i2), 1, 2.5)
E$ACCNSrandom[i3] <- runif(sum(i3), 2.5, 12)
E$ACCNSrandom[i4] <- runif(sum(i4), 12, 40)
E$ACCNSrandom[i5] <- runif(sum(i5), 40, 100)

E$ACCNSrandom