1

I have a dataframe "a" which looks like this

a1  a2  a3
a   1   45
b   2   55
c   4   34
d   3   87

and I need to convert this dataframe into a list, which looks like this

a   a2  1
a   a2  2
a   a2  4
a   a2  3
b   a3  45
b   a3  55
b   a3  34
b   a3  87

How can I do this in R?

Cath
  • 23,906
  • 5
  • 52
  • 86
Doej
  • 49
  • 7

1 Answers1

1

We create a new column with elements 'a', 'b' using Map by looping over the 2nd and 3rd columns, rbind the list elements with rbindlist and use the idcol option to create the 'grp' column from the names of the list.

 library(data.table)
 setnames(rbindlist(Map(data.frame, df1[-1], 
       letters[1:2]), idcol='grp'), 2:3, c('v1', 'v2'))[]
#   grp v1 v2
#1:  a2  1  a
#2:  a2  2  a
#3:  a2  4  a
#4:  a2  3  a
#5:  a3 45  b
#6:  a3 55  b
#7:  a3 34  b
#8:  a3 87  b

data

df1 <- read.table(text="a1  a2  a3
 a   1   45
 b   2   55
 c   4   34
 d   3   87", sep="", header=TRUE, stringsAsFactors=FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Error: could not find function "setDT" – Doej Apr 05 '16 at 06:17
  • @Doej You have to load `library(data.table)` – akrun Apr 05 '16 at 06:20
  • what is df1 and 2:3 in the command? @akrun – Doej Apr 05 '16 at 06:32
  • @Doej It is your initial dataset – akrun Apr 05 '16 at 06:33
  • 1
    @Doej THat is right and if you look at my post, I used it as `data.frame`. – akrun Apr 05 '16 at 06:36
  • I want it to be extended for N number of columns, Now how I do the same thing for a dataframe of 5X5 matrix? – Doej Apr 05 '16 at 06:54
  • 1
    @Doej You can use the same code except that use `letters[1:5]` and in the `setnames` change accordingly – akrun Apr 05 '16 at 06:57
  • If I am replacing the values of the column a1 with other characters, still in the output list it is showing the values a,b,c.. – Doej Apr 05 '16 at 07:15
  • @Doej It is because if you look at the initial dataset you used, the output doesn't seem to come from the 1st column. Are you saying the number of elements in the first column is based on the number of columns selected? – akrun Apr 05 '16 at 07:17
  • No, I just that when I replace the values of column a1(a, b,c) to a1(as, bs,cs) in the output column V2 still prints a,b,c values – Doej Apr 05 '16 at 08:08
  • 1
    @Doej It is because you are using `letters[1:3]`. instead use `df1$a1[1:3]` i.e. `setnames(rbindlist(Map(data.frame, df1[-1], df1[1:3,1]), idcol="grp"), 2:4, paste0("v", 1:3))[]` – akrun Apr 05 '16 at 08:40