【问题标题】:Extracting list title from a nested list as a variable从嵌套列表中提取列表标题作为变量
【发布时间】:2020-02-07 23:42:31
【问题描述】:

我有一个类似于此处描述的两级列表,是通过导入 CSV 创建的。

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.

我想从中生成一个热图矩阵。我使用以下解决方案将列表转换为 data.frame,然后转换为矩阵。

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

但是,当它正在转换时,我想要一个标识城市的列,它是一个列表标题。或者任何其他可以让我生成以下内容的解决方案。

City | Color | Code | Count
---------------------------

【问题讨论】:

  • 能否用dput显示数据以了解结构。即dput(head(mylist, 2))

标签: r


【解决方案1】:

1.创建reproducible minimal example:

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

2.这是一个解决方案:

    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))

返回:

    # A tibble: 2 x 4
      City    Color Code  Count
      <chr>   <fct> <fct> <fct>
    1 Toronto Blue  7600  50000
    2 Boston  Red   800   60000

【讨论】:

  • 感谢您提供可重现的最小示例,以后一定会这样做。
猜你喜欢
  • 2021-12-29
  • 1970-01-01
  • 2018-12-13
  • 2020-08-20
  • 2021-08-20
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
  • 1970-01-01
相关资源
最近更新 更多