您有两个数据框:
df <- data.frame(A = c(1,1,2,2,3,3), B = c('cat','dog','cat','dog','cat','dog'), C = c(100,200,300,400,500,600))
df2 <- data.frame(A = c(1,1,1,1,2,2,2,2,3,3,3,3), B = c('cat','dog','cat','dog','cat','dog'))
输出df1:
A B C
1 cat 100
1 dog 200
2 cat 300
2 dog 400
3 cat 500
3 dog 600
输出df2:
A B
1 cat
1 dog
1 cat
1 dog
2 cat
2 dog
2 cat
2 dog
3 cat
3 dog
3 cat
3 dog
我知道如何匹配单个值,这样当'A'值与df和df2匹配时,它会将该值添加到df2:
df2$match <- df$C[match(df2$A, df$A)]
输出:
A B match
1 cat 100
1 dog 100
1 cat 100
1 dog 100
2 cat 300
2 dog 300
2 cat 300
2 dog 300
3 cat 500
3 dog 500
3 cat 500
3 dog 500
如何匹配多个值,以便在df和df2的'A'和'B'相同时匹配'C'的值?
答案 0 :(得分:4)
您可以使用interaction
和A
之间的B
来match
,如下所示:
df2$match <- df$C[match(interaction(df2$A, df2$B), interaction(df$A, df$B))]
> df2
A B match
1 1 cat 100
2 1 dog 200
3 1 cat 100
4 1 dog 200
5 2 cat 300
6 2 dog 400
7 2 cat 300
8 2 dog 400
9 3 cat 500
10 3 dog 600
11 3 cat 500
12 3 dog 600