查找在 2 个数据帧之间匹配的行,以及它们在 R 中的索引

Finding rows which match between 2 dataframes, and the index of them in R

我有 2 个数据框。首先(我知道该怎么做)我想找到 2 个数据帧之间匹配的行(整行)。所以我可以在 A 中创建一个列,它告诉我整行是否在 B 中。但是,我不知道该怎么做的部分是找到它在 B 中的哪些索引。

TL 博士;我需要在 A 中创建一个新列,如果整行不在 B 中,它会告诉我 FALSE,或者给我该行在 B 中位置的索引。

a = as.data.frame(matrix(data = 1:10,nrow=5))
b = as.data.frame(matrix(data = c(1:5,10,7,6,9,8), nrow=5))

set.seed(02138)
b = b[sample(nrow(b)),]
rownames(b) = 1:nrow(b)
a_ = do.call("paste", a[,1:2])
b_ = do.call("paste", b[,1:2])

# Gets me TRUE/FALSE of whether there is a complete row-wise match
a$InB = a_ %in% b_

# Gets me which rows they are in b
b[b_ %in% a_,]

# Now is where I need help combining this
# Expected output

> a$InB = temp
> a
  V1 V2   InB
1  1  6 FALSE
2  2  7     3
3  3  8 FALSE
4  4  9     5
5  5 10 FALSE

您可以添加:

a$InB[a$InB] <- as.character(which(b_ %in% a_))
a
#  V1 V2   InB
#1  1  6 FALSE
#2  2  7     3
#3  3  8 FALSE
#4  4  9     5
#5  5 10 FALSE