[R] Combinations

Prof Brian D Ripley ripley at stats.ox.ac.uk
Tue Dec 14 12:14:04 CET 1999


On Mon, 13 Dec 1999, a s wrote:

> I need some help here.
> >From a vector of variable length (say, c(A,B,C,D), I need to obtain all
> posible combinations (order doesn't matter) of the elements.
> I would like a function such as:
> function(x,c(A,B,C,D))
> to give a matrix (for x=3) like:
> A B C
> A B D
> A C D
> B C D
> 
> or for x=2
> A B
> A C
> A D
> B C
> B D
> C D
> 
> And so on.
> Any ideas??

There is code to do that in Venables & Ripley, called subsets. Here's
a later version (from our forthcoming `S Programming' book)

subsets <- function(n, r, s = 1:n) {
  if(mode(n) != "numeric" || length(n) != 1
     || n < 1 || (n %% 1) != 0) stop("bad value of n")
  if(mode(r) != "numeric" || length(r) != 1
     || r < 1 || (r %% 1) != 0) stop("bad value of r")
  if(!is.atomic(s) || length(s) < n)
    stop("s is either non-atomic or too short")
  fun <- function(n, r, s)
    if(r <= 0) vector(mode(s), 0) else if(r >= n) s[1:n] else
    rbind(cbind(s[1], Recall(n - 1, r - 1, s[-1])),
          Recall(n - 1, r, s[-1]))
  fun(n, r, s)
}

Use it by

subs <- function(x, string)
  subsets(length(string), x, string)


You will need quotes! Actually, this will work for any (atomic) mode of
vector. If you have long strings,

subs <- function(x, string)
{ 
  z <- subsets(length(string), x)
  zz <- string[as.vector(z)]
  dim(zz) <- dim(z)
  zz
} 

might be better.


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list