简体   繁体   中英

Turn 3x3 data.frame into 1x9 data.frame while preserving row and column names

I am having trouble coming up with an elegant solution to this seemingly simple data manipulation problem. I can see a looped solution but I assume there is a 1-2 function single-line solution.

Here is what I have:

x <- data.frame(c1=c(1,2,3),
                c2=c(4,5,6),
                c3=c(7,8,9),
                row.names = c("r1","r2","r3"))

> x
   c1 c2 c3
r1  1  4  7
r2  2  5  8
r3  3  6  9

And here is what I want:

> y
     c1.r1 c1.r2 c1.r3 c2.r1 c2.r2 c2.r3 c3.r1 c3.r2 c3.r3
1    1     2     3     4     5     6     7     8     9

How do I manipulate x to give me y ?

Here's one way to do it:

R> unlist(lapply(x, setNames, rownames(x)))
c1.r1 c1.r2 c1.r3 c2.r1 c2.r2 c2.r3 c3.r1 c3.r2 c3.r3 
    1     2     3     4     5     6     7     8     9

A data.frame is a list, so lapply just loops over the columns. Then it sets the names of each vector to the rownames of the data.frame. Then unlist flattens the list to a vector (recursively, setting names, by default).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM