Search code examples
rcolumnsorting

Combine two columns vertically with a second column that has the names from the first column in R


For example, if I have this data frame:

column1 column2
v1      v4
v2      v5
v3      v6

How do I make a new dataframe such that it looks like this:

column3 column4
v1      column1
v2      column1
v3      column1
v4      column2
v5      column2
v6      column2

Any help is appreciated! Thank you so much!


Solution

  • You could just stack the columns together:

    stack(df)
    
      values     ind
    1     v1 column1
    2     v2 column1
    3     v3 column1
    4     v4 column2
    5     v5 column2
    6     v6 column2