R - concatenate multiple rows into one beside each other

百般思念 提交于 2020-12-13 18:25:00

问题


I have a dataframe with 3 columns and multiple rows. I want to split up the dataframe so that there is only one row and the values are in sequence (so essentially a one row csv).

My dataframe looks like this:

  **Subject    Module        ID**
    History    WW2           1
    English    Literature    2
    Maths      Algebra       3

What I am trying to achieve is one row that will look like this and in this order:

 History,    WW2,     1,     English,     Literature,    2,     Maths,    Algebra,    3 

I can do it with cut and paste using excel but was wondering was there a quick method with R.

Any help would be great! Thanks.


回答1:


Use paste with collapse to do this. unlist creates a single vector out of your dataframe, but it does it by column, so you need a t to transpose it first.

df <- read.table(textConnection("Subject    Module        ID
    History    WW2           1
                                English    Literature    2
                                Maths      Algebra       3"),
                 stringsAsFactors=FALSE, header=TRUE)
> paste(unlist(t(df)), collapse=",")
[1] "History,WW2,1,English,Literature,2,Maths,Algebra,3"

edited to add the dataframe version you asked for in the comment...

df1 <- read.csv(text=paste(unlist(t(df)), collapse=","), header=FALSE,
                stringsAsFactors=FALSE)
names(df1) <- rep(names(df), nrow(df))
> df1
  Subject Module ID Subject     Module ID Subject  Module ID
1 History    WW2  1 English Literature  2   Maths Algebra  3

This makes non-unique column names, which is not really advisable.




回答2:


data<-data.frame(A=c(1:3),B=6:8,C=9:11)
data
#    A B  C
# 1  1 6  9
# 2  2 7 10
# 3  3 8 11

paste(colnames(data),unlist(t(data)),collapse=",")
# [1] "A 1,B 6,C 9,A 2,B 7,C 10,A 3,B 8,C 11"

Hope this might help.




回答3:


If you want to keep the headings, you could try this:

  df <- read.table(textConnection("

                              Subject    Module        ID
                              History    WW2           1
                              English    Literature    2
                              Maths      Algebra       3"),stringsAsFactors=FALSE, header=TRUE)

 data.frame(t(unlist(df)))

 Subject1 Subject2 Subject3 Module1    Module2 Module3 ID1 ID2 ID3
1  History  English    Maths     WW2 Literature Algebra   1   2   3


来源:https://stackoverflow.com/questions/35990164/r-concatenate-multiple-rows-into-one-beside-each-other

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