-1

I have a two-level list similar to the one described here, created from importing CSVs.

Converting nested list to dataframe

List of 21
Toronto
        Color: Blue
        Code: 7600
        Count: 50,000
Boston
    Color: Red
    Code: 800
    Count: 60,000
etc.

I want to generate a matrix for a heat map from this. I used the following solution to convert the list to a data.frame and then matrix.

library(data.table)
rbindlist(mylist, fill=TRUE)

However, as it is being converted, I want to have a column that identifies the city which is a list title. Or alternatively any other solution that would allow me to generate the following.

City | Color | Code | Count
---------------------------
mgtrek
  • 25
  • 7
  • 2
    Can you show the data with `dput` to understand the structure. i.e. `dput(head(mylist, 2))` – akrun Feb 07 '20 at 23:44

1 Answers1

0

1.Create reproducible minimal example:

    ll <- list("Toronto" = list(
               Color= "Blue",
               Code= 7600,
               Count= 50000),
               "Boston" = list(
               Color= "Red",
               Code= 800,
               Count= 60000))

2.Here is a solution:

    library(tidyverse)       
    data.frame(ID = names(unlist(ll)),
                values = unlist(ll),
                stringsAsFactors=FALSE) %>% 
        mutate(City = gsub("\\..*", "", ID),
               measure = gsub(".*\\.", "", ID)) %>% 
        select(-ID) %>% 
        pivot_wider(names_from = measure, values_from = values) %>% 
        mutate(Count = as.numeric(Count))

Which returns:

    # A tibble: 2 x 4
      City    Color Code  Count
      <chr>   <fct> <fct> <fct>
    1 Toronto Blue  7600  50000
    2 Boston  Red   800   60000
dario
  • 6,415
  • 2
  • 12
  • 26