繁体   English   中英

R 中具有高级标准的随机数序列生成器

[英]Random number sequence generator in R with advanced criteria

我希望生成一个随机数序列,其中包含 1 和 25(含)之间的 14 个数字。 我可以在 R 中使用> sample (1:25, 14)做到这一点。 但是,对于某些序列,我需要排除某些数字(2、3、4、5、6、16、21 等)。 我还需要确保某些数字不属于序列的前 4 个数字(即 1-6、16、21 等)。我还需要某些序列,其中某些数字在第 5 位和第 14 位之间出现两次。

对不起,如果不清楚,但我基本上需要 R 中的随机数序列生成器

  • 包括排除标准
  • 指定某些数字出现在什么位置
  • 允许某个数字在某个位置之后在序列中出现两次。

如果有人知道可以做到这一点的功能,我将不胜感激。

这个函数做你想要的:

specialSample <- function(yourSample, sampleTimes, exclusion, firstFour, appearTwice){
excludedSample <- yourSample[!yourSample%in%exclusion]
first <- sample(excludedSample,1,prob=excludedSample%in%firstFour)
firstposition <- sample(1:4,1)
second <- sample(excludedSample,1,prob=excludedSample%in%appearTwice)
twice <- c(second,second)
sampler <- sample(excludedSample,sampleTimes-length(exclude),replace=TRUE)
positions <- sample(5:14,2)
result <- sampler
result[firstposition] <- first
result[positions] <- twice
return(result)
}

论据是

yourSample是您采样的序列表

sampleTimes是您想要的样本中有多少个值(如果您想要replace=FALSE我已经指定了replace=TRUE那么length(sampleTimes)必须 < length(yourSample)

exclusion是您想要排除的数字

firstFour数字,你想的一个是前四

appearTwice你希望在某些随机位置出现两次号码

 > numbers <- 1:25
 > exclude <- c(2,4,8)
 > firstFour <- 1:4
 > appearTwice <- c(11,12)

 > test <- specialSample(numbers,25,exclude,firstFour,appearTwice)
!> test
  [1] 12 23  3  9 10 10 21 12  7 17 24 15 22 12  3 14  9  9  1  6 19 15

基本思想是利用向量vec[positionN]<-value索引和采样概率来在你想要的地方获得你想要的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM