【问题标题】:Finding difference based on interaction between two vectors基于两个向量之间的相互作用寻找差异
【发布时间】:2019-08-31 01:46:18
【问题描述】:

我有两个数据框,每个数据框有两列我想比较,并生成出现在第一个数据框中的输出,这只是数据框之间比较时两列交互的差异。

我尝试使用合并、%in%、交互、匹配,但似乎无法获得正确的输出。我也在 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

谢谢!

【问题讨论】:

    标签: r dataframe


    【解决方案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))
    

    【讨论】:

      【解决方案2】:

      我们可以使用dplyr 包中的setdiff

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

      数据

      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)
      

      【讨论】:

      • 另外,在data.tablefsetdiff(datA, datB)anti_join(datA, datB) 中来自dplyr
      猜你喜欢
      • 2021-06-27
      • 1970-01-01
      • 2012-08-19
      • 2015-10-12
      • 2018-07-03
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多