[R] generate combination multiset (set with repetition)

Charles C. Berry cberry at tajo.ucsd.edu
Thu Dec 11 19:26:33 CET 2008


On Thu, 11 Dec 2008, Reuben Cummings wrote:

> Hi,
>
> This has been asked before but not sufficiently answered from what I
> could find. How do you create combinations
> with repetitions (multisets) in R?
>
> If I have
>> set <- array(1:3)

Why wrap 1:3 in array() ??

>
> And I want to choose all combinations of picking 2 numbers, I want to
> get a print out like
>
>     [,1] [,2]
> [1,]    1    1
> [2,]    1    2
> [3,]    1    3
> [4,]    2    2
> [5,]    2    3
> [6,]    3    3
>

For small problems (n < 100, say) :

 	 which( lower.tri( diag( n ), diag=TRUE), arr.ind=TRUE )[,2:1]

For larger problems, something like :

foo <- function(n) {
 	brks <- cumsum( n:1 )
 	k <- 1:choose( n+1, 2 )
 	j <- findInterval( k, brks+1 ) + 1
 	i <- k - ( brks-brks[1] )[ j ]
 	cbind( j, i ) }

If the number in 'set' are not 1:n, you can do a lookup using the results 
from above.


HTH,

Chuck



> subsets(set, 2, allow.repeat=T) should work, but I can't get the
> multic package to install, t(combn(set,2)) was suggested but it
> doesn't produce repetitions; expand.grid(rep(list(1:3), 2)) was also
> suggested, but it produces permuations, not combinations.
> Additionally, I would like to iterate through each resultant set for
> large n (similar to the description for getNextSet {pcalg}). Any
> suggestions?
>
> Reuben Cummings
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901



More information about the R-help mailing list