如何将多个列表转换为一个数据帧

时间:2017-11-12 21:24:15

标签: r

我有一个列表,告诉你个人有多少可能的配偶。它看起来像这样:

列表:

$`A1`
[1] "D2" "E2" "F2" "H2"
$`B1`
[1] "G2" "I2" "J2" "K2" "L2"
$`C1`
[1] "J2" "M2" "N2" "O2" "P2"
[6] "Q2" "R2" "S2"

因此,例如,个体A1的可能配偶是个体D2,个体E2,个体F2和个体H2。

我想把它变成一个数据框架,将个人与其可能的配对配对。所以我想要这样的东西:

DF:

Female ID   Mate ID
       A1        D2    
       A1        E2
       A1        F2
       A1        H2
       B1        G2
       B1        I2
       B1        J2
       B1        K2
       B1        L2
       C1        J2
       C1        M2
       C1        N2
       C1        O2
       C1        P2
       C1        Q2
       C1        R2
       C1        S2

4 个答案:

答案 0 :(得分:5)

我喜欢purrr:map_df来解决这个问题:

您的数据

L <- list(A1 = c("D2", "E2", "F2", "H2"),
    B1 = c("G2", "I2", "J2", "K2", "L2"),
    C1 = c("J2", "M2", "N2", "O2", "P2", "Q2", "R2", "S2"))

解决方案

library(purrr)
map_df(L, ~data.frame("Mate.ID" = .x), .id="Female.ID")

   # Female.ID Mate.ID
# 1         A1      D2
# 2         A1      E2
# 3         A1      F2
# 4         A1      H2
# 5         B1      G2
# etc

我喜欢map_df,因为有用的.id参数附加了列表条目的名称。

(这也可以写成......)

map_df(L, function(i) data.frame("Mate.ID" = i), .id="Female.ID")

(... .xfunction(i) i

的简写

答案 1 :(得分:2)

仅使用基础R的一种解决方案:

insert /*+ APPEND */ into local_table select * from table@database_link;

答案 2 :(得分:1)

您可以从底数R中使用stack-

L <- list(A1 = c("D2", "E2", "F2", "H2"),
    B1 = c("G2", "I2", "J2", "K2", "L2"),
    C1 = c("J2", "M2", "N2", "O2", "P2", "Q2", "R2", "S2"))

result <- stack(L)
names(result) <- c("MaleID", "FemaleID")

result

   MaleID FemaleID
1      D2       A1
2      E2       A1
3      F2       A1
4      H2       A1
5      G2       B1
6      I2       B1
7      J2       B1
8      K2       B1
9      L2       B1
10     J2       C1
11     M2       C1
12     N2       C1
13     O2       C1
14     P2       C1
15     Q2       C1
16     R2       C1
17     S2       C1

答案 3 :(得分:0)

> L <- list(A1 = c("D2", "E2", "F2", "H2"),
          B1 = c("G2", "I2", "J2", "K2", "L2"),
          C1 = c("J2", "M2", "N2", "O2", "P2", "Q2", "R2", "S2"))

> library(tidyverse)
> library(plyr)

> ldply(L, data.frame) %>%
  set_names("Female ID", "Mate ID")

   Female ID Mate ID
1         A1      D2
2         A1      E2
3         A1      F2
4         A1      H2
5         B1      G2
6         B1      I2
7         B1      J2
8         B1      K2
9         B1      L2
10        C1      J2
11        C1      M2
12        C1      N2
13        C1      O2
14        C1      P2
15        C1      Q2
16        C1      R2
17        C1      S2