在预算范围内创建包含所有组合的矩阵

时间:2013-12-16 19:02:28

标签: r

我正在尝试创建一个矩阵,其中包含一个范围内的所有数字组合,以使该行与特定值相加。我不确定是否有这个功能,或者我是否需要手动创建该功能。我已经尝试过组合函数,但它并没有约束总和,因此矩阵变得非常快。

示例:3行总和为5

5,0,0
4,1,0
4,0,1
3,2,0
3,0,2
3,1,1
2,3,0
2,0,3
2,2,1
2,1,2
etc..

2 个答案:

答案 0 :(得分:4)

这些组合对象称为partitions(另请参阅here甚至here),其计算由partitions包实现。

根据您的真实需要,使用以下方法之一:

library(partitions)

## The first argument says you want to enumerate all partitions in which the 
## second argument (5) is broken into three summands, each of which can take a
## maximum value of 5.
blockparts(rep(5,3),5)  ## Equiv: blockparts(c(5,5,5), 5)
#                                              
# [1,] 5 4 3 2 1 0 4 3 2 1 0 3 2 1 0 2 1 0 1 0 0
# [2,] 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0
# [3,] 0 0 0 0 0 0 1 1 1 1 1 2 2 2 2 3 3 3 4 4 5

restrictedparts(5,3)
#              
# [1,] 5 4 3 3 2
# [2,] 0 1 2 1 2
# [3,] 0 0 0 1 1

答案 1 :(得分:3)

也许这就是你想要的:

x <- expand.grid(replicate(3, list(0:5)))
x[rowSums(x) == 5, ]
#     Var1 Var2 Var3
# 6      5    0    0
# 11     4    1    0
# 16     3    2    0
# 21     2    3    0
# 26     1    4    0
# 31     0    5    0
# 41     4    0    1
# 46     3    1    1
# 51     2    2    1
# 56     1    3    1
# 61     0    4    1
# 76     3    0    2
# 81     2    1    2
# 86     1    2    2
# 91     0    3    2
# 111    2    0    3
# 116    1    1    3
# 121    0    2    3
# 146    1    0    4
# 151    0    1    4
# 181    0    0    5

expand.gridcombn有些相关,但我发现expand.grid更适用于这些类型的问题。


“gtools”包中还有permutations函数:

library(gtools)
x <- permutations(6, 3, v = 0:5, set = FALSE, repeats.allowed=TRUE)
x[rowSums(x) == 5, ]
相关问题