[SOLVED] How to check if values in one dataframe exist in another dataframe in R?


Suppose we have a data frame like this:

id  reply  user_name
1   NA     John
2   NA     Amazon
3   NA     Bob

And another data frame like this:

name  organisation
John  Amazon
Pat   Apple

Is there a way to fill in the reply column in the first data frame with 'True' or 'False' if the values in column 3 match either columns 1 or 2 in the second data frame? So for example, since John and Amazon from the second data frame exist in the first data frame, I want the first data frame to update as so:

id  reply  user_name
1   True   John
2   True   Amazon
3   False  Bob


Try this using %in% and a vector for all values:

df1$reply <- df1$user_name %in% c(df2$name,df2$organisation)


  id reply user_name
1  1  TRUE      John
2  2  TRUE    Amazon
3  3 FALSE       Bob

Some data used:

df1 <- structure(list(id = 1:3, reply = c(NA, NA, NA), user_name = c("John", 
"Amazon", "Bob")), class = "data.frame", row.names = c(NA, -3L

df2 <- structure(list(name = c("John", "Pat"), organisation = c("Amazon", 
"Apple")), class = "data.frame", row.names = c(NA, -2L))

Answered By – Duck

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.