[R] All combinations

David Winsemius dwinsemius at comcast.net
Wed Nov 30 16:35:43 CET 2011


On Nov 30, 2011, at 7:18 AM, R. Michael Weylandt wrote:

> expand.grid()
>
> This one is admittedly rather hard to find...

Well, it is linked from the `combn` help page. And it is the likely to  
be first or second in a search with ??combinations since it is in  
pkg:base and at least on my interface the displayed hits are sorted by  
alpha(pakgname), so I would disagree with it being hard to find.

Other ideas .... After replacing the missing `c` function:

 > outer(a,b,FUN=paste, sep=",")
      [,1]  [,2]  [,3]
[1,] "1,6" "1,7" "1,8"
[2,] "2,6" "2,7" "2,8"
[3,] "3,6" "3,7" "3,8"
[4,] "4,6" "4,7" "4,8"
[5,] "5,6" "5,7" "5,8"

Perhaps not what the OP asked for, but then exactly what did the OP  
ask for, anyway?

Perhaps this? (Or not.)

 > as.data.frame(sapply(a, function(x){ sapply(b, function(y)  
c(x,y),simplify=FALSE)}) )
     V1   V2   V3   V4   V5
1 1, 6 2, 6 3, 6 4, 6 5, 6
2 1, 7 2, 7 3, 7 4, 7 5, 7
3 1, 8 2, 8 3, 8 4, 8 5, 8

Interesting how print() handles data.frame columns of lists, don't you  
think?

And then, of course, building it from scratch:

 > matrix(c( rep(a, length(b)), rep(b, each=length(a))), ncol=2)
       [,1] [,2]
  [1,]    1    6
  [2,]    2    6
  [3,]    3    6
  [4,]    4    6
  [5,]    5    6
  [6,]    1    7
  [7,]    2    7
  [8,]    3    7
  [9,]    4    7
[10,]    5    7
[11,]    1    8
[12,]    2    8
[13,]    3    8
[14,]    4    8
[15,]    5    8


-- 
David.

>
> Michael
>
> On Nov 30, 2011, at 7:15 AM, Alaios <alaios at yahoo.com> wrote:
>
>> Dear all,
>> I would like something simple to do in R that I do not know how I  
>> should search for it.
>>
>> Let's say that I have a list of
>> a<-c(1,2,3,4,5)
>> b<-(6,7,8)
>> and I want to get back all their possible cominations like
>>
>> 1,6
>> 1,7
>> 1,8
>> 2,6
>> 2,7
>> 2,8
>> 3,6
>> 3,7
>> 3,8
>> and so on.
>>
>> How I can do that?
>>
>> B.R
>> Alex

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list