Home > Net >  R - list to dataframe in certain format?
R - list to dataframe in certain format?

Time:11-05

I have data structured like this (but with c. 1000 or so items):

x <- list("test1" = c("a","b","c"),
          "test2" = c("x","y"))

> x
$test1
[1] "a" "b" "c"

$test2
[1] "x" "y"

I'd like to structure it like this:

     l1 l2
1 test1  a
2 test1  b
3 test1  c
4 test2  x
5 test2  y

Ideally in a fairly fast/efficient way as my actual list is quite large

CodePudding user response:

You can use

x <- list("test1" = c("a","b","c"),
          "test2" = c("x","y"))

stack(x)

CodePudding user response:

Using enframe

library(tibble)
library(tidyr)
enframe(x, name = 'l1', value = 'l2') %>% 
    unnest(l2)
# A tibble: 5 × 2
  l1    l2   
  <chr> <chr>
1 test1 a    
2 test1 b    
3 test1 c    
4 test2 x    
5 test2 y    
  •  Tags:  
  • r
  • Related