r - 使用 R 中的条件通过键列交叉连接两个数据帧
问题描述
我有两个数据框。
mydata1=structure(list(ID_WORKES = c(58005854L, 58005854L, 58002666L,
58002666L), ID_SP_NAR = c(463L, 1951L, 21L, 465L), KOD_DEPO = c(3786L,
3786L, 1439L, 1439L), KOD_DOR = c(58L, 58L, 92L, 92L), COLUMN_MASH = c(6L,
6L, 5L, 5L), prop_violations = structure(c(1L, 2L, 2L, 2L), .Label = c("0.2",
"1"), class = "factor"), mash_score = c(0L, 2L, 2L, 2L)), .Names = c("ID_WORKES",
"ID_SP_NAR", "KOD_DEPO", "KOD_DOR", "COLUMN_MASH", "prop_violations",
"mash_score"), class = "data.frame", row.names = c(NA, -4L))
mydata2=structure(list(ID_SP_NAR = c(463L, 1951L, 21L, 465L, 500L, 600L
)), .Names = "ID_SP_NAR", class = "data.frame", row.names = c(NA,
-6L))
我需要交叉连接合并这些数据帧ID_SP_NAR
。Mydata2 仅包含关键变量 ID_SP_NAR。
我需要以这样的方式加入它,如果id_workers
没有来自 mydata2 的 ID_SP_NAR 的任何代码,那么这些代码将插入到数据集中,但对于它们在变量中prop_violations
并且mash_score
必须插入零值。
mydata2 中的IESP_ID_NAR
有这样的值
ID_SP_NAR
463
1951
21
465
500
600
ID_workes =58005854
有 463,1951 但另一个没有。并且
ID_workes =58002666
有 21 和 465,而不是 anonter!
交叉连接后的理想输出
ID_WORKES ID_SP_NAR KOD_DEPO KOD_DOR COLUMN_MASH prop_violations mash_score
1 58005854 463 3786 58 6 0.2 0
2 58005854 1951 3786 58 6 1 2
3 58005854 21 3786 58 6 0 0
4 58005854 465 3786 58 6 0 0
5 58005854 500 3786 58 6 0 0
6 58005854 600 3786 58 6 0 0
7 58002666 21 1439 92 5 1 2
8 58002666 465 1439 92 5 1 2
9 58002666 500 1439 92 5 0 0
10 58002666 600 1439 92 5 0 0
11 58002666 463 1439 92 5 0 0
12 58002666 1951 1439 92 5 0 0
KOD_DEPO,KOD_DOR,COLUMN_MASH 有固定值,也必须保存。
怎么做?
merge(mydata1,mydata2, by = ID_SP_NAR)
不工作(我尝试通过左连接使用不起作用),它不会插入我想要的零。
解决方案
我们可以使用complete
fromtidyr
根据第二个数据集中的“ID_WORKES”和“ID_SP_NAR”的值来扩展数据集
library(tidyverse)
mydata1 %>%
mutate_if(is.factor, as.character) %>%
complete(ID_WORKES, ID_SP_NAR = mydata2$ID_SP_NAR,
fill = list(prop_violations = '0', mash_score = 0)) %>%
fill(3:5)
# A tibble: 12 x 7
# ID_WORKES ID_SP_NAR KOD_DEPO KOD_DOR COLUMN_MASH prop_violations mash_score
# <int> <int> <int> <int> <int> <chr> <dbl>
# 1 58002666 21 1439 92 5 1 2
# 2 58002666 463 1439 92 5 0 0
# 3 58002666 465 1439 92 5 1 2
# 4 58002666 500 1439 92 5 0 0
# 5 58002666 600 1439 92 5 0 0
# 6 58002666 1951 1439 92 5 0 0
# 7 58005854 21 1439 92 5 0 0
# 8 58005854 463 3786 58 6 0.2 0
# 9 58005854 465 3786 58 6 0 0
#10 58005854 500 3786 58 6 0 0
#11 58005854 600 3786 58 6 0 0
#12 58005854 1951 3786 58 6 1 2
推荐阅读
- r - 如何为包括管道的代码创建循环
- node.js - nodejs中的简单http服务器:响应时间1毫秒很多吗?
- python - 计算 POS 标记模式的出现次数
- java - 将枚举映射到Java中代码量较少的另一个枚举
- pytorch - 将图像馈送到堆叠的 resnet 块以创建嵌入
- maui - MAUI MyApp.WinUI 未正常运行
- r - 政府宣布变更后如何更新时区信息?
- salesforce - Salesforce 自动触发流
- mockito - 如何在 Spring Boot 应用程序中为 JDBC 模板编写 Mockito Junit 测试用例?
- android - 在 android TV Leanback 中从遥控器的后退按钮隐藏键盘