Home > Net >  R Match two string columns between two different dataframes
R Match two string columns between two different dataframes

Time:09-02

I have 'df1' with data that look like this:

Object Thing
apple tini drink
vodka cran beverage
tom collins alcohol
arnie palmer cocktail

And I have 'df2' with data that look like this:

Object1 Thing1
apple tini drink
vodka cran bever
tom collins alc
arnie palmer cocktail

I am looking to check and see if Object and Thing from df1 match any Object1 and Thing1 from df2, and if they do match, a 1 is created in a new column in df1 and if they don't, a 0 is created, so that it looks like this:

Object Thing Value
apple tini drink 1
vodka cran beverage 0
tom collins alc 0
arnie palmer cocktail 1

Note that columns are intentionally different in case they don't match is the actual dataframe.

Thank you!

CodePudding user response:

Making an extra column and then left_joining solves this:

library(tidyverse)

df3 <- mutate(df2, Value = 1)

left_join(df1, df3, by=c("Object" = "Object1",
                         "Thing" = "Thing1")) %>%
  mutate(Value = replace_na(Value, 0))

#    Object    Thing Value
# 1    tini    drink     1
# 2    cran beverage     0
# 3 collins  alcohol     0
# 4  palmer cocktail     1
  • Related