1

I have smth like this,

> ex <- data.frame(a = 1:20, b = 20:1, c = c(letters[1:10],letters[1:10]))
> head(ex, n = 3)
    a  b c
  1 1 20 a
  2 2 19 b
  3 3 18 c

and I want to convert it in smth like this

> head(df2list2(df = ex,namecol = "c"), n = 2)
$a
    a  b
1   1 20
11 11 10

$b
    a  b
2   2 19
12 12  9

The ugly bunch of code I have used in this function is the following:

df2list2 <- function(df,namecol){
 nc = which(colnames(df)==namecol)
 nl = list()
 names = unique(df[,nc])
 for (i in names){
   tmp = df[df[,nc] == i,]
   nl[[i]] = tmp[,-nc]
 }
 return(nl)
}

It is dreadfully slow and not very elegant, I may try to do smth more efficient but I just wanted to know if there is an easy workaround to do this transformation.

David Mas
  • 1,149
  • 2
  • 12
  • 18

0 Answers0