transform named list to dataframe

Asked

Viewed 91 times

0

I’d like to turn a nominated list into a data.frame (or Tibble) where the name of the object in the list becomes an observation in the data.frame

The example list I have is this:

mylist <- list(a_palette = c("#2A363B", "#019875", "#99B898", "#FECEA8", 
"#FF847C", "#E84A5F", "#C0392B", "#96281B"), ppalette = c("#F7DC05", 
"#3d98d3", "#EC0B88", "#5e35b1", "#f9791e", "#3dd378", "#c6c6c6", 
"#444444"), bpalette = c("#c62828", "#f44336", "#9c27b0", "#673ab7", 
"#3f51b5", "#2196f3", "#29b6f6", "#006064", "#009688", "#4caf50", 
"#8bc34a", "#ffeb3b", "#ff9800", "#795548", "#9e9e9e", "#607d8b"))

I would like to get as a result data like this:

dt <- tibble(palette = c("a_palette", "ppalette", "bpalette"),
       hex = c('"#2A363B", "#019875", "#99B898", "#FECEA8", 
"#FF847C", "#E84A5F", "#C0392B", "#96281B"', '"#F7DC05", 
"#3d98d3", "#EC0B88", "#5e35b1", "#f9791e", "#3dd378", "#c6c6c6", 
"#444444"', '"#c62828", "#f44336", "#9c27b0", "#673ab7", 
"#3f51b5", "#2196f3", "#29b6f6", "#006064", "#009688", "#4caf50", 
"#8bc34a", "#ffeb3b", "#ff9800", "#795548", "#9e9e9e", "#607d8b"'))

head(dt)

# A tibble: 3 x 2
  palette   hex                                   
  <chr>     <chr>                                 
1 a_palette "\"#2A363B\", \"#019875\", \"#99B898\~
2 ppalette  "\"#F7DC05\", \n\"#3d98d3\", \"#EC0B8~
3 bpalette  "\"#c62828\", \"#f44336\", \"#9c27b0\~

I was trying something with the command stack(mylist); but I ended up finding no way out. Someone has would have some solution?

1 answer

2


As you want the hexa quoted codes, you need a bit of string manipulation:

dt <- data.frame(
  palette = names(mylist),
  hex = Reduce(rbind,
               sub("$", "'", sub("^", "'",
                   lapply(mylist, paste, collapse = "', '")))),
  row.names = 1:length(names(mylist))
)

But if it is to store the palettes in an object, keeping as list can be more practical.

  • Thanks for commenting. But, in this solution I do not have the column "Hex".

  • I edited the answer, see if that’s what you need.

  • Thank you, Carlos, that’s what I was trying to do. There are some operations there that I didn’t even imagine. As I said, it may be easier to work with lists, but I have little practice with them, so for me, it’s better to use data.frame. Thanks!

  • data.frame is a special list case, the access of named elements is equal: mylist$bpalette or mylist[["bpalette"]]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.