[R] sequence of vectors

Gregory Warnes gregory.warnes at mac.com
Mon Nov 19 19:06:07 CET 2007



Well, this is a natural thing to program up using 3 nested 'for',  
loops.  Alternatively, one could use something like:

 > combn <- function( ..., l=list(...) )
+ {
+   lens  <- sapply( args, length)
+   ncomb <- prod(lens)
+   retval <- matrix(ncol=length(args), nrow=ncomb)
+   for(i in 1:length(args))
+     {
+       retval[,i] <- rep(args[[i]], length=ncomb)
+     }
+   retval
+ }
 > combn(a=1:3, b=4:5, c=6:8)
       [,1] [,2] [,3]
[1,]    1    4    6
[2,]    2    5    7
[3,]    3    4    8
[4,]    1    5    6
[5,]    2    4    7
[6,]    3    5    8
[7,]    1    4    6
[8,]    2    5    7
[9,]    3    4    8
[10,]    1    5    6
[11,]    2    4    7
[12,]    3    5    8
[13,]    1    4    6
[14,]    2    5    7
[15,]    3    4    8
[16,]    1    5    6
[17,]    2    4    7
[18,]    3    5    8


On Nov 19, 2007, at 9:59AM , Marc Bernard wrote:

> Dear All,
>
>   I wonder if there is any R function to generate a sequence of  
> vectors from existing ones. For example:
>   x 1<- c(1,2,3)
>   x2 <- c(4,5)
>   x3 <- c(6,7,8)
>
>   The desired output is a list of all 3*2*3 = 18 possible  
> combinations of elements of x1,x2 and x3. One element for example  
> is (1,4,6).
>
>   Many thanks in advance,
>
>   Bernard
>
>
>
>
> ---------------------------------
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.



More information about the R-help mailing list