首页 > 解决方案 > 合并 2 个不同大小的数据框

问题描述

我有 2 个要合并的数据框。在df12个不同的日子记录观察。每条记录都有一个索引,id1 个人识别号,id2 指的是录制日期的编号(天必须不同)。还有一个 Day 变量记录录制时的星期几。

仅根据df2序列号和 id1 个人识别号记录观察结果。每人只有一次观察。同样,这里还有一个 Day 变量,用于记录录制的时间。

我想确定 df2 中与 df1 同一天记录的观察结果。

我怎样才能做到这一点?

样本数据

df1:

    structure(list(index = c(11011202, 11011202, 11011202, 11011202, 
11011203, 11011203, 11011207, 11011207, 11011207, 11011207, 11011209, 
11011209, 11011209, 11011209, 11011210, 11011210, 11011210, 11011210, 
11011211, 11011211, 11011211, 11011211, 11011212, 11011212, 11011212, 
11011212, 11011212, 11011212, 11011212, 11011212, 11011213, 11011213, 
11011213, 11011213, 11011213, 11011213, 11011217, 11011217, 11011219, 
11011219, 11011220, 11011220, 11011220, 11011220, 11011220, 11011220, 
11020202, 11020202, 11020202, 11020202), id1 = c(1, 1, 4, 4, 
1, 1, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 
2, 3, 3, 4, 4, 1, 1, 3, 3, 4, 4, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 
1, 1, 2, 2), id2 = c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 
1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 
2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2), Day = c(5, 1, 5, 
1, 1, 3, 4, 7, 4, 7, 4, 1, 4, 1, 5, 7, 5, 7, 1, 2, 1, 2, 7, 2, 
7, 2, 7, 2, 7, 2, 7, 4, 7, 4, 7, 4, 4, 1, 3, 1, 1, 2, 1, 2, 1, 
2, 4, 7, 4, 7)), row.names = c(NA, -50L), class = c("tbl_df", 
"tbl", "data.frame"))

df2:

    structure(list(Day = c(3, 3, 4, 6, 6, 6, 7, 7, 7, 7, 4, 4, 6, 
6, 6, 4, 3, 7, 7, 5, 5, 7, 5, 6, 6), index = c(11011209, 11011209, 
11011210, 11011212, 11011212, 11011213, 11011213, 11011220, 11011220, 
11020208, 11020212, 11020212, 11020301, 11020301, 11020301, 11020305, 
11020310, 11020315, 11020315, 11020316, 11020316, 11020320, 11020606, 
11020611, 11020611), id1 = c(1, 2, 2, 1, 2, 1, 4, 1, 2, 2, 1, 
2, 1, 2, 3, 1, 1, 1, 2, 1, 2, 2, 1, 1, 2)), row.names = c(NA, 
-25L), class = c("tbl_df", "tbl", "data.frame"))

标签: rdataframe

解决方案


两个数据集都有duplicate by变量,导致join. 一种选择是nest通过这些变量,然后进行连接

library(dplyr)
library(tidyr)
df2 %>%
      group_by(Day, index) %>%
      nest %>%
      left_join(df1 %>% 
                   rename(idnew = id1)) %>% 
      unnest(data)

推荐阅读