How to combine all rows into a single row? [closed]

别等时光非礼了梦想. 提交于 2019-12-30 14:44:09

问题


I have a dataframe which has 100 rows and 10 columns, i wonder how I can merge all the 100 rows into just one row? Thanks.

mydata=seq(1,1000)
mydata=as.data.frame(matrix(mydata,nrow = 100,ncol = 10,byrow=T))

the result should be like this:(just a single row)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 ……

回答1:


We can get the transpose and concatenate to a vector. Note that the transpose converts to a matrix and there is no need to call as.matrix.

as.vector(t(mydata))

Or we can use unlist after splitting the rows into a list.

unlist(lapply(seq_len(nrow(mydata)), function(i) mydata[i,]))



回答2:


Matrix are indexed by column so I am guessing you may just need to transpose your data and then construct a new matrix from it:

matrix(t(as.matrix(mydata)), nrow = 1)

Or you can convert it to a vector after the transposing depending on what you need:

as.vector(t(as.matrix(mydata)))


来源:https://stackoverflow.com/questions/38387031/how-to-combine-all-rows-into-a-single-row

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