2

I was searching the interwebs for a way to create a data frame from a list but retain the names of the list elements as a column by itself. I saw this from back in 2014 but a lot of the functions are deprecated and/or none of them are doing what I'm trying to do.

Here's what I've done so far but it's a hacky way of doing it.

RNGkind("Mersenne-Twister")
set.seed(42)

my_list <- list(a = rnorm(22, 4, 1),
                b = sample(1:1000, 10, replace = T),
                c = rep(1334, 5))

my_df <- data.frame(names = rep(names(my_list), do.call(c, lapply(my_list, length))),
      values = do.call(c, my_list))

Is there a more elegant way of accomplishing this? I'm not much of a tidyverse or tidyr but I'm up for anything if it's more streamlined than this.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
Lalochezia
  • 497
  • 4
  • 15

1 Answers1

2

We can use stack from base R

my_df2 <- stack(my_list)[2:1]
all.equal(my_df, my_df2, check.attributes = FALSE)
#[1] TRUE

Or with tidyverse

library(tibble)
library(tidyr)
enframe(my_list) %>%
   unnest(value)
akrun
  • 874,273
  • 37
  • 540
  • 662