I guess you could just separately compute the combinations of each size using combn
and then use do.call
with rbind
to combine them all together:
allcombo <- function(long1, max1s) {
do.call(rbind, lapply(1:max1s, function(num1) {
t(apply(combn(long1, num1), 2, function(x) {
col = rep(0, long1)
col[x] = 1
col
}))
}))
}
I've stored your posted solution in function OP
. We can check they return the same values:
all.equal(OP(20, 5), allcombo(20, 5))
# [1] TRUE
Now we can benchmark (there are 21699 returned rows):
library(microbenchmark)
microbenchmark(OP(20, 5), allcombo(20, 5))
# Unit: milliseconds
# expr min lq median uq max neval
# OP(20, 5) 242.4120 256.5791 269.7237 292.7131 556.5984 100
# allcombo(20, 5) 150.4291 179.2588 188.4840 200.9898 448.2214 100
So this approach using combn
is a bit faster (30% on my computer for this set of parameters).