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?
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
You could read the help for expand.grid very carefully for the answer to this
question.
---------------------------------------------------------------------------
Jeff Newmiller The ..... ..... Go Live...
DCN:<jdnewmil at dcn.davis.ca.us> Basics: ##.#. ##.#. Live
Go...
Live: OO#.. Dead: OO#.. Playing
Research Engineer (Solar/Batteries O.O#. #.O#. with
/Software/Embedded Controllers) .OO#. .OO#. rocks...1k
---------------------------------------------------------------------------
Sent from my phone. Please excuse my brevity.
Antje Niederlein <niederlein-rstat at yahoo.de> 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?
>
>______________________________________________
>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.