1

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.

kennyi
  • 23
  • 1
  • 5

3 Answers3

5

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.

cory
  • 6,529
  • 3
  • 21
  • 41
  • Would there be a way of repeating the column names as well and then saving it as a dataframe rather than as a vector? Thanks for your help – kennyi Mar 14 '16 at 15:58
  • Thanks @cory, I eventually got what I needed from your first answer and edited my question to the original question as the answer worked. – kennyi Mar 14 '16 at 17:45
1
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.

Sowmya S. Manian
  • 3,723
  • 3
  • 18
  • 30
0

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
Wyldsoul
  • 1,468
  • 10
  • 16