问题
So I've seen similar versions of this question asked before (Getting all combinations which sum up to 100 using R) but I'm struggling to find a way to figure out what I need to run specifically. I'm trying to create a list in R of all the different combinations of 6 numbers that add up to 10. However, I want to include 0s and repeats of the same # in the row. So it would look something like this:
10 0 0 0 0 0
9 1 0 0 0 0
8 2 0 0 0 0
I've tried running the following:
C = t(restrictedparts(10,6, include.zero=TRUE))
ComboSet<-data.frame(do.call(rbind, lapply(1:nrow(C),function(i) getall(iterpc(table(C[i,]), order=T)))))
However, when I do this it does not seem to include the variations that have 0s in them. I've tried entering the include.zero=TRUE function into different parts of what I'm running but I've had no luck so far. Any suggestions?
回答1:
This is a good question and the answer isn't very obvious.
There are many things to address here. For starters, make sure that you include the
libraries that you use in your example. I know from experience that you are using partitions
and iterpc
. From the partitions
documentation, we see that there is a function that returns exactly what you are looking for without any additional steps. It is the compositions
function which generates Integer Compositions.
myComps <- t(as.matrix(compositions(10, 6)))
head(myComps)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 10 0 0 0 0 0
[2,] 9 1 0 0 0 0
[3,] 8 2 0 0 0 0
[4,] 7 3 0 0 0 0
[5,] 6 4 0 0 0 0
[6,] 5 5 0 0 0 0
dim(myComps)
[1] 3003 6
all(rowSums(myComps) == 10)
[1] TRUE
As for fixing your actual code, I'm not exactly sure why your code is not working as is. I've used iterpc
in the past and remember explicitly using that same approach. Anywho, the workaround is to explicitly declare the labels
parameter as the frequency of each element is being used instead of the value itself.
## The 1's should be 0's and the 2's should be 10's
ComboSet[1:6, ]
X1 X2 X3 X4 X5 X6
1 1 1 1 1 1 2
2 1 1 1 1 2 1
3 1 1 1 2 1 1
4 1 1 2 1 1 1
5 1 2 1 1 1 1
6 2 1 1 1 1 1
## OP's original code
ComboSet<-data.frame(do.call(rbind, lapply(1:nrow(C),function(i) getall(iterpc(table(C[i,]), order=T)))))
all(rowSums(ComboSet) == 10)
[1] FALSE
table(rowSums(ComboSet))
7 8 9 10 11 12 13 14 15 16
12 30 150 255 186 690 420 420 180 660
## Here is the fix with labels explicitly declared
ComboSetFix <- data.frame(do.call(rbind, lapply(1:nrow(C), function(i) {
getall(iterpc(table(C[i,]), labels = as.integer(names(table(C[i,]))), order=T))
})))
all(rowSums(ComboSetFix) == 10)
[1] TRUE
dim(ComboSetFix)
[1] 3003 6
You should know that iterpc
is not being actively maintained and users are encouraged to switch to arrangements
. It has a different interface, so you can't simply replace the word "iterpc" with "arrangements".
来源:https://stackoverflow.com/questions/58383926/finding-a-list-of-all-combinations-of-6-numbers-that-add-up-to-10