简体   繁体   中英

Compare two data.frames to find the rows in data.frame 1 and data.frame 2 which have equal values in selected columns

I have 2 data frames (a1 and a2)

a1
A   B   C   D
1   A   6   8
2   D   7   3 #**
3   X   3   3

a2
A   B   C   D
4   D   2   3 #**
5   Z   3   5
6   X   3   4


a1 <- data.frame(
  A = 1:3,
  B = c("A", "D", "X"),
  C = c(6, 7, 3),
  D = c(8, 3, 3)
)
a2 <- data.frame(
  A = 4:6,
  B = c("D", "Z", "X"),
  C = c(2, 3, 3),
  D = c(3, 5, 4)
)

I want to get the tuples (a1$A,a2$A) for the rows which have the same values in colums B and D

In this example, I would get (2,4) because they have the same values in colums B and D, respectively D and 3

Use merge to merge the data frames.

merged <- merge(a1, a2, c("B", "D"))
subset(merged, select = c(A.x, A.y))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM