【问题标题】:Convert list of lists to data frame retaining names and all columns将列表列表转换为保留名称和所有列的数据框
【发布时间】:2019-10-15 02:10:30
【问题描述】:

我想将化学公式转换为一个数据框,其中包含 1) 矿物名称、2) 化学公式和 3) 从公式中提取的每个元素的一组列。我得到了前两列,我可以使用 CHNOSZ::makeup() 从每个公式中提取元素的数量。但是,我不熟悉使用列表,也不知道如何将列表 rbind() 重新放入包含我正在寻找的所有内容的数据框中(即参见上面的 1-3)。

这是我目前所拥有的 - 感谢任何帮助(包括指向如何将数据从嵌套列表转换为数据框的优秀教程的链接)。

library(tidyverse)
library(CHNOSZ)

formulas <- structure(list(Mineral = c("Abelsonite", "Abernathyite", "Abhurite", 
"Abswurmbachite", "Acanthite", "Acetamide"), Composition = c("C31H32N4Ni", 
"K(UO2)(AsO4)4(H2O)", "Sn3O(OH)2Cl2", "CuMn6(SiO4)O8", "Ag2S", 
"CH3CONH2")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-6L))

test <-  formulas %>% 
  select(Composition) %>% 
  map(CHNOSZ::makeup) %>%
  flatten

test2 <- do.call(rbind,test)

    > test2
     As  H  K  O  U
[1,] 31 32  4  1 31
[2,]  4  2  1 19  1
[3,]  2  2  3  3  2
[4,]  1  6 12  1  1
[5,]  2  1  2  1  2
[6,]  2  5  1  1  2

这是不对的。

【问题讨论】:

    标签: r tidyverse nested-lists


    【解决方案1】:

    你可以这样做

    library(tidyverse)
    library(CNOSZ)
    test <-  formulas %>%
        mutate(res = map(Composition, ~stack(makeup(.x)))) %>%
        unnest(cols = res) %>%
        spread(ind, values)
    ## A tibble: 6 x 17
    #  Mineral Composition     C     H     N    Ni    As     K     O     U    Cl
    #  <chr>   <chr>       <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
    #1 Abelso… C31H32N4Ni     31    32     4     1    NA    NA    NA    NA    NA
    #2 Aberna… K(UO2)(AsO…    NA     2    NA    NA     4     1    19     1    NA
    #3 Abhuri… Sn3O(OH)2C…    NA     2    NA    NA    NA    NA     3    NA     2
    #4 Abswur… CuMn6(SiO4…    NA    NA    NA    NA    NA    NA    12    NA    NA
    #5 Acanth… Ag2S           NA    NA    NA    NA    NA    NA    NA    NA    NA
    #6 Acetam… CH3CONH2        2     5     1    NA    NA    NA     1    NA    NA
    ## … with 6 more variables: Sn <dbl>, Cu <dbl>, Mn <dbl>, Si <dbl>, Ag <dbl>,
    ##   S <dbl>
    

    【讨论】:

      猜你喜欢
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 2019-06-05
      • 1970-01-01
      相关资源
      最近更新 更多