随机排列

要生成 5 个数字的随机排列:

sample(5)
# [1] 4 5 3 1 2

要生成任何向量的随机排列:

sample(10:15)
# [1] 11 15 12 10 14 13

也可以使用包 pracma

randperm(a, k)
# Generates one random permutation of k of the elements a, if a is a vector,
# or of 1:a if a is a single integer.
# a: integer or numeric vector of some length n.
# k: integer, smaller as a or length(a).

# Examples
library(pracma)
randperm(1:10, 3)
[1] 3 7 9

randperm(10, 10)
[1]  4  5 10  8  2  7  6  9  3  1

randperm(seq(2, 10, by=2))
[1]  6  4 10  2  8