列出从 m 中抽取 n 个带替换的数字的所有方法 < n values (i.o.w.: all partitionings of a set of size n into m distinct subsets) in R [duplicate]

问题描述 投票:0回答:1

在模拟研究中,我需要生成所有不同的方法来生成 1 到 n (n>m) 之间的 m 数字序列,使得数字之和为 n,即

nums <- c(n_1, n_2, ..., n_m)

有限制

min(num) > 0 & sum(nums) == n

换句话说:一组 n 元素可能划分为 m 不同的子集。我知道这种分区的数量是“第二类斯特林数”,这对于大 n 来说是不可行的,但对于小 n 我需要它。

请注意,这与查找所有排列是不同的问题,在本线程中对此进行了回答。相反,它是关于分区的。

r combinatorics
1个回答
3
投票

partitions 包 (GitHub) 中,

partitions::compositions(n, m, include.zero)
应该可以解决问题。在这里,
n
表示每个向量的总和,
m
表示该向量的元素数量,
include.zero=FALSE
确保不存在零。

partitions::compositions(n=5, m=2, include.zero=FALSE) |> t()
# [1,] 4 1
# [2,] 3 2
# [3,] 2 3
# [4,] 1 4
© www.soinside.com 2019 - 2024. All rights reserved.