我尝试在 Sheldon M. Ross 的 Simulation (2006, 4ed., Elsevier)
中使用 R 实现一个示例,它想要生成一个随机排列,内容如下:
假设我们有兴趣生成数字 1,2,... ,n 的排列
所有 n!可能的顺序是同样可能的。
下面的算法将通过
- 首先随机选择数字1,2,...,n中的一个;
- 然后把那个数字放在位置n;
- 然后它随机选择剩余的 n-1 个数字中的一个并将该数字放在位置 n-1 ;
- 然后它随机选择剩余的 n-2 个数字中的一个并将其放在位置 n-2 ;
- 等等
当然,我们可以轻松实现数字 1,2,...,n 的随机排列
sample(1:n, replace=FALSE)
例如
> set.seed(0); sample(1:5, replace=FALSE)
[1] 1 4 3 5 2
但是,我想按照上面的算法步骤手动得到类似的结果。那我试试
## write the function
my_perm = function(n){
x = 1:n # initialize
k = n # position n
out = NULL
while(k>0){
y = sample(x, size=1) # choose one of the numbers at random
out = c(y,out) # put the number in position
x = setdiff(x,out) # the remaining numbers
k = k-1 # and so on
}
out
}
## test the function
n = 5; set.seed(0); my_perm(n) # set.seed for reproducible
有
[1] 2 2 4 5 1
这显然是不正确的,因为有两个 2
。我该如何解决这个问题?
最佳答案
您已经正确地实现了逻辑,但您只需要注意一件事,它与 R
相关。
来自 ?sample
If x has length 1, is numeric (in the sense of is.numeric) and x >= 1, sampling via sample takes place from 1:x
所以当最后一个数字留在 x
中时,假设数字是 4,采样将从 1:4 开始并从中返回任何 1 数字。
例如,
set.seed(0)
sample(4, 1)
#[1] 2
所以你需要调整你的功能,然后代码才能正常工作。
my_perm = function(n){
x = 1:n # initialize
k = n # position n
out = NULL
while(k>1){ #Stop the while loop when k = 1
y = sample(x, size=1) # choose one of the numbers at random
out = c(y,out) # put the number in position
x = setdiff(x,out) # the remaining numbers
k = k-1 # and so on
}
out <- c(x, out) #Add the last number in the output vector.
out
}
## test the function
n = 5
set.seed(0)
my_perm(n)
#[1] 3 2 4 5 1
关于r - 在 R 中生成随机排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69415035/