[R] How to expand.grid with string elements (the half!)

William Dunlap wdunlap at tibco.com
Mon Jun 10 18:55:55 CEST 2013


Perhaps the OP wants the unique combinations of V1 and V2, as in
  R> d <- expand.grid(V1=c("x","y","z"),V2=c("x","y","z"))
  R> d[ as.numeric(d$V1) <= as.numeric(d$V2), ]
    V1 V2
  1  x  x
  4  x  y
  5  y  y
  7  x  z
  8  y  z
  9  z  z
or
  R> V <- letters[24:26]
  R> rbind(t(combn(V,m=2)), cbind(V,V))
       V   V  
  [1,] "x" "y"
  [2,] "x" "z"
  [3,] "y" "z"
  [4,] "x" "x"
  [5,] "y" "y"
  [6,] "z" "z"

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Rolf Turner
> Sent: Monday, June 10, 2013 2:20 AM
> To: Gundala Viswanath
> Cc: r-help at stat.math.ethz.ch
> Subject: Re: [R] How to expand.grid with string elements (the half!)
> 
> 
> Your question makes no sense at all.  The grid expansion
> has 9 rows.  In case you hadn't noticed, 9 is an odd number
> (i.e. not divisible by 2).  There are no "halves".
> 
> Do not expect the list to read your mind.  Instead, ask a
> meaningful question.
> 
>      cheers,
> 
>          Rolf Turner
> 
> On 10/06/13 17:25, Gundala Viswanath wrote:
> > I have the following result of expand grid:
> >
> >> d <- expand.grid(c("x","y","z"),c("x","y","z"))
> > What I want is to create a combination of strings
> > but only the half of the all combinations:
> >
> >    Var1 Var2
> > 1    x    x
> > 2    y    x
> > 3   y    y
> > 4   z    y
> > 5   x    z
> > 6    z    z
> >
> >
> > What's the way to do it?
> 
> ______________________________________________
> 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