[R] Combinations question

Martin Maechler maechler at stat.math.ethz.ch
Wed Aug 9 18:49:40 CEST 2006


>>>>> "Jacques" == Jacques VESLOT <jacques.veslot at 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



More information about the R-help mailing list