Unlist a data frame by rows, not columns

馋奶兔 提交于 2019-11-26 14:45:30

问题


A relatively simple question, but the answer seems to have eluded me. Currently, I have a data frame which looks similar to this:

0   0   0   1   1
0   1   0   1   1
2   1   1   0   3

I'm trying to turn this into a single line of data, by rows. I used the unlist function, and it did what I wanted, but gave them to me by columns. It gave me this:

0,0,2,0,1,1,0,0,1,1,1,0,1,1,3

but what I want is this:

0,0,0,1,1,0,1,0,1,1,2,1,1,0,3

I apologize if this seems like a silly question, but I'm still a novice with R. Any help (or referrals to functions which might help me process this) would be greatly appreciated.


回答1:


We can take the transpose (t) of the dataset and then use c to get a vector output

 c(t(df1))
 #[1] 0 0 0 1 1 0 1 0 1 1 2 1 1 0 3

By doing transpose, we convert the 'data.frame' to 'matrix'. In both data.frame or matrix, unlist/c operations happen columnwise. So, transposing swaps the columns for rows and viceversa and we get the expected result.




回答2:


You can try also as.vector():

x<-matrix(c(0,0,2,0,1,1,0,0,1,1,1,0,1,1,3),3,5)

x
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    1    1
[2,]    0    1    0    1    1
[3,]    2    1    1    0    3

as.vector(t(x))
[1] 0 0 0 1 1 0 1 0 1 1 2 1 1 0 3


来源:https://stackoverflow.com/questions/31989270/unlist-a-data-frame-by-rows-not-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!