Denis
Denis

Reputation: 12087

Convert data.frame to list of lists

I am trying to figure out how to convert a data.frame to a list of lists. Suppose I had (feel free to modify this if you need to capture more attributes for later):

v <- list(
          row1=list(col1 = as.Date("2011-01-23"), col2="A"), 
          row2=list(col1 = as.Date("2012-03-03"), col2="B"))
d <- do.call(rbind, lapply(v, as.data.frame))
d$col3 <- 2

How do I get d back to a list of lists (similar to v). The end result should be equivalent to the result of:

vr <- list(
          row1=list(col1 = as.Date("2011-01-23"), col2="A", col3=2), 
          row2=list(col1 = as.Date("2012-03-03"), col2="B", col3=2))

Upvotes: 2

Views: 85

Answers (2)

Lunalo John
Lunalo John

Reputation: 335

You have to go through the columns again making them lists before you pass them as values of the element of the main list. I hope the below code helps:

apply(d,MARGIN = 1, FUN=function(x){as.list(x)})

Upvotes: 2

markus
markus

Reputation: 26373

You can do

out <- lapply(split(d, rownames(d)), as.list)
out
#$row1
#$row1$col1
#[1] "2011-01-23"

#$row1$col2
#[1] "A"

#$row1$col3
#[1] 2


#$row2
#$row2$col1
#[1] "2012-03-03"

#$row2$col2
#[1] "B"

#$row2$col3
#[1] 2

If you add stringsAsFactors = FALSE when creating d, i.e.

d <- do.call(rbind, lapply(v, as.data.frame, stringsAsFactors = FALSE))
d$col3 <- 2

then

identical(out, vr)

returns TRUE.

Upvotes: 5

Related Questions