Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

r

I have the following result of expand grid:

d <- expand.grid(c("x","y","z"),c("x","y","z"))

Note the vector could be longer than 3 and string length could be greater or of different pattern?

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
like image 487
pdubois Avatar asked Sep 10 '26 21:09

pdubois


1 Answers

You can get rid of the duplicates (x - y == y - x) by first sorting the rows in your data, and then getting rid of the duplicates using duplicated:

d2 = t(apply(d, 1, sort))
d2[!duplicated(d2),]
     [,1] [,2]
[1,] "x"  "x" 
[2,] "x"  "y" 
[3,] "x"  "z" 
[4,] "y"  "y" 
[5,] "y"  "z" 
[6,] "z"  "z" 

Alternatively, you can use combn to get the combinations, then you only need some data tinkering to get what you need:

levs = c("x", "y", "z")
comb_level1 = combn(levs, 1)
comb_level2 = combn(levs, 2)
t(cbind(rbind(comb_level1, comb_level1), comb_level2))
     [,1] [,2]
[1,] "x"  "x" 
[2,] "y"  "y" 
[3,] "z"  "z" 
[4,] "x"  "y" 
[5,] "x"  "z" 
[6,] "y"  "z"

I think the solution using duplicated is better.

like image 72
Paul Hiemstra Avatar answered Sep 12 '26 14:09

Paul Hiemstra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!