两个数据帧共享行的逻辑

时间:2021-10-15 22:53:43

How do I get the logicals of shared rows of two data frames?

如何获得两个数据帧共享行的逻辑?

> a <- data.frame(x = 1:5, y = 7:11)
> b <- data.frame(x = c(4, 2, 6, 3, 3, 1), y = c(10, 16, 7, 9, 9, 7))
> a
  x  y
1 1  7
2 2  8
3 3  9
4 4 10
5 5 11
> b
  x  y
1 4 10
2 2 16
3 6  7
4 3  9
5 3  9
6 1  7
> a.indices <- c(TRUE, FALSE, TRUE, TRUE, FALSE)
> b.indices <- c(TRUE, FALSE, FALSE, TRUE, TRUE, TRUE)

I would like to return a.indices or b.indices.

我想退货。指数或b.indices。

1 个解决方案

#1


2  

You can do a combinaton of what merge and %in% does

您可以对merge和%in%做一个组合

a.indices <- match(
  do.call(paste, c(a, sep="\r")), 
  do.call(paste, c(b, sep="\r")), nomatch=0
)>0

You combine the rows into a single value and then use match to compare one set to the other. You could also do

将行合并为一个值,然后使用match将一个集合与另一个集合进行比较。你也可以做

b.indices <- Reduce(function(vprev,vnow) vprev & !is.na(vnow), 
    Map(match, b,a), init=T)

(for both these methods you can swap a and b to get the opposite result). You may wish to test to compare performance in your specific scenario.

(对于这两种方法,你可以交换a和b以得到相反的结果)。您可能希望测试在您的特定场景中比较性能。

#1


2  

You can do a combinaton of what merge and %in% does

您可以对merge和%in%做一个组合

a.indices <- match(
  do.call(paste, c(a, sep="\r")), 
  do.call(paste, c(b, sep="\r")), nomatch=0
)>0

You combine the rows into a single value and then use match to compare one set to the other. You could also do

将行合并为一个值,然后使用match将一个集合与另一个集合进行比较。你也可以做

b.indices <- Reduce(function(vprev,vnow) vprev & !is.na(vnow), 
    Map(match, b,a), init=T)

(for both these methods you can swap a and b to get the opposite result). You may wish to test to compare performance in your specific scenario.

(对于这两种方法,你可以交换a和b以得到相反的结果)。您可能希望测试在您的特定场景中比较性能。