r - 基于R中的列标题合并两个表
问题描述
想根据列标题合并两个表:
因此,我想将 TableA 和 TableB 与左连接合并,并希望得到 OutputTable 中提到的输出。
为了进一步解释,OutputTable 应该是这样的:
1) 关联 TableA 中的所有列标题
2) 将 TableB 中存在的数据粘贴到类似的列中。
3) TableB 中不存在的 TableA 列的数据为 0
TableA <- data.frame(
action = c(0, 1, 1, 0, 0),
actor = c(1, 1, 1, 1, 0),
also = c(1, 0, 1, 1, 1),
anim = c(1, 1, 0, 1, 1),
appear = c(0, 0, 1, 0, 1))
TableB <- data.frame(
action = c(1, 0, 0, 0, 0),
actor = c(0, 1, 0, 1, 0),
also = c(1, 0, 0, 1, 1),
bear = c(0, 1, 1, 0, 1),
book = c(1, 0, 0, 0, 1),
appear = c(0, 0, 1, 0, 1))
OutputTable <- data.frame(
action = c(1, 0, 0, 0, 0),
actor = c(0, 1, 0, 1, 0),
also = c(1, 0, 0, 1, 1),
anim = c(0, 0, 0, 0, 0),
appear = c(0, 0, 1, 0, 1))
所以
最终的
解决方案
我们可以创建两个基于intersect
和的索引setdiff
nm1 <- intersect(names(TableA), names(TableB))
nm2 <- setdiff(names(TableA), names(TableB))
通过子集与“TableA”相同的“TableB”列创建新数据集,将“TableA”中不同的列设置为 0
df3 <- TableB[nm1]
df3[nm2] <- 0
df3
# action actor also appear anim
#1 1 0 1 0 0
#2 0 1 0 0 0
#3 0 0 0 1 0
#4 0 1 1 0 0
#5 0 0 1 1 0
如果order
列的重要,
library(tidyverse)
bind_rows(TableA, TableB, .id = 'grp') %>%
select_if(~ !is.na(.[1])) %>%
filter(grp == 2) %>%
select(-grp) %>%
mutate_all(replace_na, 0)
# action actor also anim appear
#1 1 0 1 0 0
#2 0 1 0 0 0
#3 0 0 0 0 1
#4 0 1 1 0 0
#5 0 0 1 0 1
推荐阅读
- python - Python中点和MultiPolygon Geoseries对象之间的距离
- python-3.x - 这是什么意思:“OpenSSL 1.1.0g 2017 年 11 月 2 日(库:OpenSSL 1.1.1a 2018 年 11 月 20 日)”
- elasticsearch - Highresult 不显示在模糊查询 Elasticsearch 结果中
- mapbox-gl-js - Mapbox 缩放到活动数据
- sql-server - SQL 加密/解密数字
- javascript - 如何将 axios 响应传递给函数参数?
- maven - Maven - 使用 jar 作为依赖项时获得不同的版本 -> 令人困惑
- javascript - 如何在模板字符串中添加换行符
- xcode - 在 OS 10.14.3 和 Xcode 9.0 下与 LAPACK 库链接
- cygwin - 使用 rgbasm 的 Cygwin 中的“常量表达式错误中的非常量操作数”