[英]Find the combinations that add up to a number, followed by the next number until 0 - in R
I am trying to create a matrix of all the combinations that add up to a number followed by the combinations that add up to the next number until 0. For example我正在尝试创建一个矩阵,其中包含加起来为一个数字的所有组合,然后是加起来为下一个数字的组合,直到 0。例如
Input: N = 3
Output:
[1,]3 0
[2,]2 1
[3,]1 1 1
[4,]2 0
[5,]1 1
[6,]1 0
[7,]0
My question is, is there a package in R that can do this?我的问题是,R中是否有一个package可以做到这一点? or do I have to write my own function?
还是我必须自己写 function?
I would really appreciate any help or guidance on this.我真的很感激任何帮助或指导。 Thank you.
谢谢你。
I think I have figured out the solution using the library partitions .我想我已经找到使用库分区的解决方案。
library(partitions)
n=7
df = t(as.matrix(blockparts(rep(n,n),n, include.fewer = FALSE))) # create a transposed matrix with the possible combinations
indx <- !duplicated(t(apply(df, 1, sort))) # find non - duplicates in sorted rows
df[indx, ] # select only the non - duplicates according to that index
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.