为了确保采样均匀,您可以生成所有排列并将其限制为总和为 7 的排列:
library(gtools)
perms <- permutations(8, 7, 0:7, repeats.allowed=T)
perms7 <- perms[rowSums(perms) == 7,]
From nrow(perms7)
,我们看到只有 1716 种可能的排列,总和为 7。现在您可以从排列中均匀采样:
set.seed(144)
my.perms <- perms7[sample(nrow(perms7), 100000, replace=T),]
head(my.perms)
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] 0 0 0 2 5 0 0
# [2,] 1 3 0 1 2 0 0
# [3,] 1 4 1 1 0 0 0
# [4,] 1 0 0 3 0 3 0
# [5,] 0 2 0 0 0 5 0
# [6,] 1 1 2 0 0 2 1
这种方法的优点是很容易看出我们是随机均匀采样的。而且,它的速度相当快——构建perms7
在我的计算机上花了 0.3 秒构建 100 万行my.perms
花了 0.04 秒。如果您需要绘制许多向量,这将比递归方法快得多,因为您只是使用矩阵索引perms7
而不是单独生成每个向量。
以下是样本中数字计数的分布:
# 0 1 2 3 4 5 6 7
# 323347 188162 102812 51344 22811 8629 2472 423