Getting all combinations which sum up to 100 using R -
i need combinations sum equal 100 using 8 variables take value 0 100 incremental step of 10. (i.e. 0, 10, 20 ... 100)
the following script inefficient creates huge dataset , wondering if had better way of doing this.
x <- expand.grid("on" = seq (0,100,10), "3m" = seq(0,100,10), "6m" = seq(0,100,10), "1y" = seq(0,100,10), "2y" = seq(0,100,10), "5y" = seq(0,100,10), "10y" = seq(0,100,10), "15y" = seq(0,100,10)) x <- x[rowsums(x)==100,]
edit --
to answer question stéphane laurent
the result should like
on 3m 6m 1y 2y 5y 10y 15y 100 0 0 0 0 0 0 0 90 10 0 0 0 0 0 0 80 20 0 0 0 0 0 0 70 30 0 0 0 0 0 0 60 40 0 0 0 0 0 0 50 50 0 0 0 0 0 0 (...) 0 0 0 0 0 0 10 90 0 0 0 0 0 0 0 100
followed stéphane laurent's answer, able super fast solution using uniqueperm2
function here.
library(partitions) c = t(restrictedparts(10,8)) do.call(rbind, lapply(1:nrow(c),function(i)uniqueperm2(c[i,])))
update, there faster solution using iterpc
package.
library(partitions) library(iterpc) c = t(restrictedparts(10,8)) do.call(rbind, lapply(1:nrow(c),function(i) getall(iterpc(table(c[i,]), order=t))))
it twice speed of uniqueperm2
> f <- function(){ do.call(rbind, lapply(1:nrow(c),function(i)uniqueperm2(c[i,]))) } > g <- function(){ do.call(rbind, lapply(1:nrow(c),function(i) getall(iterpc(table(c[i,]), order=t)))) } > microbenchmark(f(),g()) unit: milliseconds expr min lq mean median uq max neval cld f() 36.37215 38.04941 40.43063 40.07220 42.29389 46.92574 100 b g() 16.77462 17.45665 19.46206 18.10101 20.65524 64.11858 100
Comments
Post a Comment