如何使用 grep 或任何其他方法比较两个数据框中的不同行数并获得匹配和不匹配?

How to use grep or any other method to compare different no of row in two data frame and get the match and mismatch?

下面是我的两个数据框:

ABData1 <- data.frame(id=c(11,12,13,14,15),
                      a = c(1,2,3,4,5))
ABData2 <- data.frame(id=c(11,12,13,14),
                      b = c(1,4,3,4))

如何比较这两个数据框的匹配行和不匹配行

如果 a 的 ABData1 的第一行与 b 的 ABData2 的第一行匹配,则显示为匹配,否则显示为不匹配,然后转到第二行....所有比较将按行进行。

我试过下面的代码,它对一个数据帧工作正常,但由于两个数据帧中的行不同,它出现了错误。

ABData <- data.frame(a = c(1,2,2,1,1),
                     b = c(1,2,1,1,2))

    match<- ABData %>% rowwise() %>% filter(grepl(a,b, fixed = TRUE))
    
    mismatch<- ABData %>% rowwise() %>% filter(!grepl(a,b))

我期望低于输出

Expected match Output:

id    a     expected    b
11    1     1           1
13    3     3           3
14    4     4           4
Expected mismatch output:

id    a     expected    b
12    2     2           4
15    NA    NA          5

提前致谢。

你可以使用这个:

ABData1 <- data.frame(a = c(1,2,3,4,5))
ABData2 <- data.frame(b = c(1,4,3,4))

equLength <- function(x, y) {
  if (length(x)>length(y)) length(y) <- length(x) else length(x) <- length(y)
  data.frame(a=x, b=y)
}

ABData <- equLength(ABData1$a, ABData2$b)

...然后将您的工作代码用于一个数据帧。

library("dplyr")
resultMatch <- ABData %>% rowwise() %>% filter(grepl(a,b, fixed = TRUE))
resultMismatch <- ABData %>% rowwise() %>% filter(!grepl(a,b))

扩展问题:

library("dplyr")

ABData1 <- data.frame(id=c(11,12,13,14,15),  a = c(1,2,3,4,5))
ABData2 <- data.frame(id=c(11,12,13,14),  b = c(1,4,3,4))

equLength <- function(x, y) {
  if (length(x)>length(y)) length(y) <- length(x) else length(x) <- length(y)
  data.frame(a=x, b=y)
}

if (nrow(ABData1)>nrow(ABData2)) ABData <- data.frame(ABData1, b=equLength(ABData1$a, ABData2$b)$b) else
  ABData <- data.frame(ABData2, a=equLength(ABData1$a, ABData2$b)$a)
  
resultMatch <- ABData %>% rowwise() %>% filter(grepl(a,b, fixed = TRUE))
resultMismatch <- ABData %>% rowwise() %>% filter(!grepl(a,b))