[R] unique combinations

peter dalgaard pdalgd at gmail.com
Wed Dec 21 11:12:25 CET 2011


On Dec 21, 2011, at 08:59 , Antje Niederlein wrote:

> Hi there,
> 
> I have a vector and would like to create a data frame, which contains
> all unique combination of two elements, regardless of order.
> 
> myVec <- c(1,2,3)
> 
> what expand.grid does:
> 
> 1,1
> 1,2
> 1,3
> 2,1
> 2,2
> 2,3
> 3,1
> 3,2
> 3,3
> 
> what I would like to have
> 
> 1,1
> 1,2
> 1,3
> 2,2
> 2,3
> 3,3
> 
> Can anybody help?

I almost said combn(), but that won't give you the same element twice. So either

> rbind(cbind(1:3,1:3),t(combn(3,2)))
     [,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    3    3
[4,]    1    2
[5,]    1    3
[6,]    2    3

or

> e <- expand.grid(1:3,1:3)
> e[e[,1]<=e[,2],]
  Var1 Var2
1    1    1
4    1    2
5    2    2
7    1    3
8    2    3
9    3    3

or maybe 

> subset(expand.grid(1:3,1:3),Var1 <= Var2)
  Var1 Var2
1    1    1
4    1    2
5    2    2
7    1    3
8    2    3
9    3    3




-- 
Peter Dalgaard, Professor
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list