【发布时间】:2018-06-16 03:19:21
【问题描述】:
有没有一种方法可以在 R 中生成随机整数,使得任何两个连续数字都不同?它可能与x[k+1] != x[k] 类似,但我不知道如何将它们组合在一起。
【问题讨论】:
-
您是从一组固定的整数中生成的吗?您可以直接取样而不更换吗?
有没有一种方法可以在 R 中生成随机整数,使得任何两个连续数字都不同?它可能与x[k+1] != x[k] 类似,但我不知道如何将它们组合在一起。
【问题讨论】:
另一种方法是过采样并删除不合格的,如下所示:
# assumptions
n <- 5 # population size
sample_size <- 1000
# answer
mu <- sample_size * 1/n
vr <- sample_size * 1/n * (1 - 1/n)
addl_draws <- round(mu + vr, 0)
index <- seq(1:n)
sample_index <- sample(index, sample_size + addl_draws, replace = TRUE)
qualified_sample_index <- sample_index[which(diff(sample_index) != 0)]
qualified_sample_index <- qualified_sample_index[1:sample_size]
# In the very unlikely event the number of qualified samples < sample size,
# NA's will fill the vector. This will print those N/A's
print(which(is.na(qualified_sample_index) == TRUE))
【讨论】:
不确定是否有可用的功能。也许这个功能可以做你想做的事:
# n = number of elements
# sample_from = draw random numbers from this range
random_non_consecutive <- function(n=10,sample_from = seq(1,5))
{
y=c()
while(length(y)!=n)
{
y= c(y,sample(sample_from,n-length(y),replace=T))
y=y[!c(FALSE, diff(y) == 0)]
}
return(y)
}
例子:
random_non_consecutive(20,c(2,4,6,8))
[1] 6 4 6 2 6 4 2 8 4 2 6 2 8 2 8 2 8 4 8 6
希望这会有所帮助。
上面的函数有很长的最坏情况运行时间。例如,我们可以通过以下实现使最坏情况保持不变:
# n = number of elements
# sample_from = draw random numbers from this range
random_non_consecutive <- function(n=10,sample_from = seq(1,5))
{
y= rep(NA, n)
prev=-1 # change this if -1 is in your range, to e.g. max(sample_from)+1
for(i in seq(n)){
y[i]=sample(setdiff(sample_from,prev),1)
prev = y[i]
}
return(y)
}
【讨论】:
letters[random_non_consecutive(10,seq(letters))]。第二种选择:使用我后来添加的函数random_non_consecutive(10,letters)。让我知道这是否能解决您的问题