2

After looking at another post about column names and combn function here consider the same data.frame. We make a combn with all 2 possible vectors:

foo <- data.frame(x=1:5,y=4:8,z=10:14, w=8:4)
all_comb <- combn(foo,2)

Is there a way to keep column names after the combn call so in this case we could get "x y" instead of "X1.5 X4.8" as shown below ?

comb_df <- data.frame(all_comb[1,1],all_comb[2,1])
print(comb_df)

  X1.5 X4.8
1    1    4
2    2    5
3    3    6
4    4    7
5    5    8
Community
  • 1
  • 1
  • [This][1] might be what you're looking for. [1]: http://stackoverflow.com/questions/20919037/set-column-names-while-calling-a-function –  Mar 31 '15 at 19:06

1 Answers1

0

I suspect you really want to use expand.grid() instead.

Try this:

head(expand.grid(foo))

  x y  z w
1 1 4 10 8
2 2 4 10 8
3 3 4 10 8
4 4 4 10 8
5 5 4 10 8
6 1 5 10 8

or

head(expand.grid(foo[, 1:2]))

  x y
1 1 4
2 2 4
3 3 4
4 4 4
5 5 4
6 1 5
Andrie
  • 176,377
  • 47
  • 447
  • 496
  • Thank you for your help Andrie. Actually, my point is to use the combn function to get all the possible 2-combinations (a,b) of the 4 vectors (x,y,z,w). I managed to do it, but the column names are not kept in memory, is it somehow possible to do it ? – user3794465 Jan 23 '15 at 09:47