r - 在 R 中生成随机排列
问题描述
我尝试使用Simulation (2006, 4ed., Elsevier)
Sheldon M. Ross 的 R in 来实现一个示例,它想要生成一个随机排列,内容如下:
假设我们有兴趣生成数字 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
如果 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
推荐阅读
- python - 更快地检索区块的总 eth 交易价值
- ruby-on-rails - Elasticsearch 在 localhost 中运行良好,但在测试时出现连接错误
- sql-server - 数据库无法打开,因为它是869版本。此服务器支持852及更早版本
- design-patterns - 哪种设计模式适合从多个来源获取相同类型的数据,将它们组合成一个单元并应用多个过滤器
- javascript - 如何在 vuejs 中全局使用变量
- json - Arduino UART ESP01,json parse 4with 433 MHZ 接收器和发射器
- javascript - 上传 expo 文件错误(错误:位置不可读)
- monaco-editor - 是否有任何 API 可用于更改现有的 monaco 编辑器构造选项?
- selenium - org.openqa.selenium.ElementNotInteractableException:元素不可交互:[object HTMLTextAreaElement] 没有大小和位置
- javascript - 如何使用 history.goBack 与链接选项卡而不返回到先前选择的选项卡