so13eit
so13eit

Reputation: 952

R transforming list of lists to data frame with list number as column

What feels like a really simple question that I'm just stuck on. I'm trying to break out a list of lists into a 2-column data frame with the list number as a column.

Sample Data:

d <- list("1" =c("ad","af"), "2" =c("bc","bd","be"))
> d
$`1`
[1] "ad" "af"

$`2`
[1] "bc" "bd" "be"

Desired output:

ID    Value
1     ad
1     af
2     bc
2     bd
2     be

A for loop would do the job but I'm trying to avoid that. The unlist function actually accomplishes slightly more than I'd like, as it lists out in the names the list name followed by the element number:

unlist(d)
  11   12   21   22   23 
"ad" "af" "bc" "bd" "be" 

Thanks!

Upvotes: 2

Views: 95

Answers (3)

tguzella
tguzella

Reputation: 1481

A quick way:

as.data.frame(do.call(rbind, 
  mapply(function(id, vals) cbind(ID = id, Value = vals), names(d), d, SIMPLIFY = FALSE)))

Upvotes: 0

Miguel
Miguel

Reputation: 91

Try:

unlist(d, use.names=FALSE)  
"ad" "af" "bc" "bd" "be"

Upvotes: 0

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

You can simply use:

stack(d)
#  values ind
#1     ad   1
#2     af   1
#3     bc   2
#4     bd   2
#5     be   2

Upvotes: 5

Related Questions