convert named list with mixed content to data frame

  • A+
Category:Languages

Is there a better and nicer way to convert named list with mixed content to data frame?

The working example:

my_list <- list("a" = 1.0, "b" = "foo", "c" = TRUE)  my_df <- data.frame(   "key" = names(my_list),   stringsAsFactors = F )  my_df[["value"]] <- unname(my_list) 

Is it possible to do this conversion in one step?

 


We can use stack from base R

stack(my_list) 

According to ?stack

The stack function is used to transform data available as separate columns in a data frame or list into a single column that can be used in an analysis of variance model or other linear model. The unstack function reverses this operation.


Or with enframe

library(tidyverse) enframe(my_list) %>% # creates the 'value' as a `list` column    mutate(value = map(value, as.character)) %>% # change to single type    unnest  

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: