Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert named list with mixed content to data frame

Tags:

dataframe

r

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?

like image 949
RSzT Avatar asked Nov 09 '18 17:11

RSzT


1 Answers

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 
like image 106
akrun Avatar answered Sep 20 '22 15:09

akrun