Question

I have this dataframe :

data=structure(list(X3CO = c(24.88993835, 25.02366257, 24.90308762), X3CS = c(25.70629883,25.26747704, 25.1953907), X3CD = c(26.95723343, 26.84725571, 26.2314415)), .Names = c("X3CO", "X3CS", "X3CD"), class = "data.frame", row.names = c(NA, -3L))

> data
      X3CO     X3CS     X3CD
1 24.88994 25.70630 26.95723
2 25.02366 25.26748 26.84726
3 24.90309 25.19539 26.23144

What I would like to do is to make a new dataframe taking all the row into one column and the column name into a second column :

24.88994 X3CO
25.02366 X3CO
24.90309 X3CO
25.70630 X3CS  
25.26748 X3CS

Do you know a simple way to do that ?

Edit : is there a way to add an ID that respect the order of ind ?

24.88994 X3CO 1
25.02366 X3CO 1
24.90309 X3CO 1
25.70630 X3CS 2
25.26748 X3CS 2
Was it helpful?

Solution

Faster , and using R-base:

 stack(data)
       values  ind
1 24.88993835 X3CO
2 25.02366257 X3CO
3 24.90308762 X3CO
4 25.70629883 X3CS
5 25.26747704 X3CS
6 25.19539070 X3CS
7 26.95723343 X3CD

OTHER TIPS

> library(reshape2)
> melt(data)
Using  as id variables
  variable    value
1     X3CO 24.88994
2     X3CO 25.02366
3     X3CO 24.90309
4     X3CS 25.70630
5     X3CS 25.26748
6     X3CS 25.19539
7     X3CD 26.95723
8     X3CD 26.84726
9     X3CD 26.23144

Easy peasy! You'll want to check out the reshape2 package for all its data shaping abilities

library(reshape2)

melt(data)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top