基于两个向量之间的交互寻找差异

3
我有两个每个有两列的数据框需要比较,我想生成仅出现在第一个数据框中的输出,即当在数据框之间比较两列的交互时得到的差异。
我尝试使用合并(merge)、%in%、Interaction、match等方法,但似乎无法得到正确的输出。我也在SO上进行了广泛搜索,但没有找到类似的问题。
我找到的最接近的响应是:
newdat <- match(interaction(dfA$colA, dfA$colB), interaction(dfB$colA, dfB$colB))

但显然,这段代码不正确,因为如果它能工作的话,会给我一个在数据框之间共同的东西,而我想要的是它们之间的差异(出现错误-它生成一个数字向量,当colA和B都是字符串时)。

数据示例:

#Dataframe A

    colA     colB
    Aspirin  Smith, John
    Aspirin  Doe, Jane
    Atorva   Smith, John
    Simva    Doe, Jane

#Dataframe B
    colA     colB
    Aspirin  Smith, John
    Aspirin  Doe, Jane
    Atorva   Doe, Jane

## GOAL: 

#Dataframe
    colA     colB
    Atorva   Smith, John
    Simva    Doe, Jane

谢谢!

2个回答

2
我们可以使用包中的setdiff函数。"最初的回答"。
library(dplyr)

setdiff(datA, datB)
#     colA        colB
# 1 Atorva Smith, John
# 2  Simva   Doe, Jane

DATA

datA <- read.table(text = "    colA     colB
    Aspirin  'Smith, John'
    Aspirin  'Doe, Jane'
    Atorva   'Smith, John'
    Simva    'Doe, Jane'",
                   header = TRUE, stringsAsFactors = FALSE)

datB <- read.table(text = "    colA     colB
    Aspirin  'Smith, John'
    Aspirin  'Doe, Jane'
    Atorva   'Doe, Jane'",
                   header = TRUE, stringsAsFactors = FALSE)

2
此外,在 data.table 中,可以使用 fsetdiff(datA, datB) 或使用 dplyr 中的 anti_join(datA, datB) - akrun

1
如果您想要使用基础的 R 解决方案,编写一个 setdiffDF 函数很容易。
setdiffDF <- function(x, y){
  ix <- !duplicated(rbind(y, x))[nrow(y) + 1:nrow(x)]
  x[ix, ]
}


setdiffDF(dfA, dfB)
#    colA        colB
#3 Atorva Smith, John
#4  Simva   Doe, Jane

数据以 dput 格式展示。
dfA <-
structure(list(colA = structure(c(1L, 1L, 2L, 3L), 
.Label = c("Aspirin", "Atorva", "Simva"), class = "factor"), 
colB = structure(c(2L, 1L, 2L, 1L), .Label = c("Doe, Jane", 
"Smith, John"), class = "factor")), class = "data.frame", 
row.names = c(NA, -4L))

dfB <-
structure(list(colA = structure(c(1L, 1L, 2L), 
.Label = c("Aspirin", "Atorva"), class = "factor"), 
colB = structure(c(2L, 1L, 1L), .Label = c("Doe, Jane", 
"Smith, John"), class = "factor")), class = "data.frame", 
row.names = c(NA, -3L))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接