I have this R function to generate a matrix of all combinations of k numbers between 0 and n whose sum equals n. This is one of the bottlenecks of my program as it becomes extre
See the partitions package partitcularly compositions() and blockparts() they'll be faster both as whole matrix generators and for iterative operation. Then if that still isn't fast enough see the wide variety of publications on composition and partition generation algorithms (loopless, gray code, and parallel) like Daniel Page's research.
library(partitions)
library(microbenchmark)
# rcpp_comps is an Rcpp implementation of compositions using loop
# free grey code, just for illustrative purposes.
# Just get the matrix
microbenchmark( compositions(3,10), compositions(10,3),
blockparts(rep(10,3),10), blockparts(rep(3,10),3),
rcpp_comps(10), times=10)
## Unit: microseconds
## expr min lq median uq max neval
## compositions(3, 10) 1967.4 2050.9 2097.1 2173 3189.6 10
## compositions(10, 3) 618.2 638.5 654.6 688 700.7 10
## blockparts(rep(10, 3), 10) 612.2 620.8 645.6 663 963.5 10
## blockparts(rep(3, 10), 3) 2057.2 2089.2 2176.0 2242 3116.4 10
## rcpp_comps(10) 359.9 360.7 367.6 378 404.2 10