Re: [R] Combinations question

From: Martin Maechler <maechler_at_stat.math.ethz.ch>
Date: Thu 10 Aug 2006 - 02:49:40 EST

>>>>> "Jacques" == Jacques VESLOT <jacques.veslot@good.ibl.fr> >>>>> on Wed, 09 Aug 2006 17:33:05 +0200 writes:

    Jacques> library(gtools)
    Jacques> cb <- function(n,r) t(apply(combinations(n, r), 1, function(x) ifelse(1:n %in% x, 1, 0)))

    Jacques> cb(6,3)

Several months ago, when this came up as well, I had summarized the diverse 'combinations' approaches and found that really the one from package
"combinat" (rather than "gtools") was best. The function there is called combn().

Also, the next version of R (R-2.4.0) will contain an (even slightly faster) version of that, i.e., if you dare to use "R-devel", you have combn() available from ``standard R''... and that's another reason why I'd recommend using the "combinat" version rather than the "gtools" one.

Martin Maechler, ETH Zurich

    Jacques> Martin Chlond a écrit :

>> I need to generate a {0,1} matrix wifht nCr rows and n
>> columns. The rows of the matrix will consist of all
>> possible combinations containing r ones.

>> My clumsy attempt for n = 6 and r = 3 is
>>
>> X <- expand.grid(c(1,0),c(1,0),c(1,0),c(1,0),c(1,0),c(1,0))
>> Y <- X[rowSums(X)==3,]

>> I can genralize this in a function but the result is
>> quite ugly. Any suggestions?

>> Thank you in advance.
>>
>> Martin



R-help@stat.math.ethz.ch 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. Received on Thu Aug 10 06:08:50 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 10 Aug 2006 - 08:20:26 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.