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 
                                                  )  )  ) ) )

简单的矢量化解决方案:

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

这是做你想做的一种方法。

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
链接地址: http://www.djcxy.com/p/24878.html

上一篇: 创建一个可变长度的随机样本矢量

下一篇: R:如果另一个矢量中的值在x和y之间,则范围之间的随机数