r - 合并 2 个不同大小的数据框
问题描述
我有 2 个要合并的数据框。在df1
2个不同的日子记录观察。每条记录都有一个索引,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"))
解决方案
两个数据集都有duplicate
by
变量,导致join
. 一种选择是nest
通过这些变量,然后进行连接
library(dplyr)
library(tidyr)
df2 %>%
group_by(Day, index) %>%
nest %>%
left_join(df1 %>%
rename(idnew = id1)) %>%
unnest(data)
推荐阅读
- java - JSON 解析错误:无法反序列化 ArrayList 的实例
- java - 如何使用 gdx-gamesvcs 将游戏数据保存到云端?
- amazon-web-services - 如何在两个不同的 AWS 区域对同一用户进行身份验证?
- c++ - 以指定字符结束输入流,例如“|”?
- mongodb - 如何加载 MongoDB 客户端并在 F# Interactive 中启动连接?
- java - AppCompatButton 不使用选择器更改文本或背景
- python - Python 用 docx 库编写 word 文件
- c# - .NET Core MVC SignalR 集线器方法未同时运行
- jquery - 与 jquery 数据表反应 - NotFoundError:Node.removeChild:要删除的节点不是该节点的子节点
- openlayers - 测量和分割海岸线