I want to match the values of two columns in two data frames and add a third column, it's better to see the data frames:
FromA <- c("a", "b", "d")
ToA <- c("a", "k", "h")
PAC<- c("red", "blue", "black")
df1 <- data.frame(FromA, ToA, PAC)
> df1
FromA ToA PAC
1 a a red
2 b k blue
3 d h black
FromB<- c("a", "b", "f")
ToB <- c("a", "k", "h")
df2<- data.frame(FromB, ToB)
> df2
FromB ToB
1 a a
2 b k
3 f h
I want the second data frame to get the value of df1$PAC
, if the value of the two first columns match.
the final result:
> DF2
FromB ToB PAC
1 a a red
2 b k blue
3 f h NA
So, I used sapply()
df2$PAC<- sapply(1:nrow(df2), function(i)
df1$PAC[df1$FromA==df2$FromB[i] & df1$ToA == df2$ToB[i] ])
The function works if the two columns match completely, otherwise, it gives me an error.
Could you help me to understand what I'm missing? I'd appreciate it.