将列表列表转换为保留名称和所有列的数据框

Convert list of lists to data frame retaining names and all columns

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

这是我目前所知道的 - 感谢任何帮助(包括 link 一个关于如何将数据从嵌套列表转换为数据帧的好教程)。

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

这是不对的。

你可以这样做

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>