首页 > 解决方案 > 基于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))

在此处输入图像描述

所以

在此处输入图像描述

最终的

在此处输入图像描述

标签: r

解决方案


我们可以创建两个基于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

推荐阅读