user6644063 user6644063 - 4 months ago 12
R Question

list - reorganise data.frames columns into rows

I have got a list that contains 10 data.frames, which have 4 columns each one. I need to reorganise the data.frames in order to convert the columns into rows, by keeping also the column names.

Here an example of one of my data.frame within the list:

[[10]]
x y z k
1 24 20 15 13
2 25 15 25 13
3 25 14 20 13


My output, for each data.frame, should be:

[[10]]
1 x
2 24
3 25
4 25
5 y
6 20
7 15
8 14
9 z
10 15
11 25
12 20
13 k
14 13
15 13
16 13


I think I can solve it with lapply but I am not aware of any function that can do the trick.

Any hint?

Thanks

Answer

For one of your data frames:

> d
   x  y  z  k
1 24 20 15 13
2 25 15 25 13
3 25 24 20 13

You can get a vector of the values with column names with:

> c(rbind(names(d),as.matrix(d)))
 [1] "x"  "24" "25" "25" "y"  "20" "15" "24" "z"  "15" "25" "20" "k"  "13" "13"
[16] "13"

Note the character conversion.

If you want a one-column data frame of characters then:

> data.frame(M=c(rbind(names(d),as.matrix(d))), stringsAsFactors=FALSE)
    M
1   x
2  24
3  25
4  25
5   y
6  20
7  15
8  24
9   z
10 15
11 25
12 20
13  k
14 13
15 13
16 13

No need for add-on packages.

Write that as a function and lapply-it to a list of such things.

md = function(d){data.frame(M=c(rbind(names(d),as.matrix(d))), stringsAsFactors=FALSE)}
ldf = list(d,d,d)
lapply(ldf, md)
Comments