简体   繁体   中英

R - Match two columns in two dataframes

I'm trying to manipulate a dataframe where certain conditions are met.

There's the main dataframe df1:

Title             Artist        Warner    Sony    Universal
Break My Heart    Dua Lipa      0         0       0
Daisies           Katy Perry    0         0       1
Nicotine          Chef`Special  1         1       0
... 1 000 000+ rows

df2:

Label       Title            Artist        Operation
Warner      Nicotine         Chef`Special  0
Sony        Break my Heart   Dua Lipa      1
... 100+ rows

Df1 contains some mistakes. In this case Nicotine has Warner value 1 while it should be 0. I'm looking to match Title and Artist from both dataframes and then changing the label value to either 1 or 0 depending on df2.

In this instance it should see that Nicotine by Chef'Special is in df1 and df2, and it should change df1$Warner to 0. Break My Heart by Dua Lipa should have df1$Sony set to 1 using the same method.

I have been thinking about how to tackle this for quite some time but I'm at a complete loss.

Here is one option using merge, didn't have your data so used mtcars as an example:

df1 = head(mtcars, 5)
df2 = subset(head(within(df1,mpg <-  mpg * 2),2), select = "mpg")


df3 <- merge(df1, df2, by = 0, all.x = TRUE)
df3 <- within(df3, mpg <- ifelse(is.na(mpg.y), 
                              mpg.x, mpg.y))[-(2:3)]

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