1

I would like to combine a list of character vectors into a single data frame. For example, I want

list(A=c("123","456"), B=c("789"), C=c("000"))

to become:

  label val
1     A 123
2     A 456
3     B 789
4     C 000

I came up with the following. It works, but it seems clunky. Is there a more elegant way to do the above?

l <- list(A=c("123","456"), B=c("789"), C=c("000"))
res <- lapply(names(l), function(x) { 
    data.frame(label=rep(x, length(l[[x]])), val=l[[x]], 
        stringsAsFactors = F) })
do.call("rbind", res)
patrickmdnet
  • 3,332
  • 1
  • 29
  • 34

2 Answers2

2
library(tidyverse)

test <- list(A=c("123","456"), B=c("789"), C=c("000"))
enframe(test, "label", "val") %>% unnest
lkq
  • 2,326
  • 1
  • 12
  • 22
2

You can use good old fashioned base R.

stack(l)
#   values ind
# 1    123   A
# 2    456   A
# 3    789   B
# 4    000   C
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245