首页 > 解决方案 > 在 R 中生成随机排列

问题描述

我尝试使用Simulation (2006, 4ed., Elsevier)Sheldon M. Ross 的 R in 来实现一个示例,它想要生成一个随机排列,内容如下:

当然,我们可以通过以下方式轻松实现数字 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. 我该如何解决这个问题?

标签: ralgorithmpermutation

解决方案


您已经正确实现了逻辑,但您只需要注意与R.

?sample

如果 x 的长度为 1,是数字(在 is.numeric 的意义上)并且 x >= 1,则通过 sample 进行采样从 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

推荐阅读