staove7
staove7

Reputation: 580

Moving rows from one dataframe to another based on a matching column

I'm very sorry for asking this question, because I saw something similar in the past but I couldn't find it (so duplication will be understandable).

I have 2 data frames, and I want to move all my (matching) customers who appears in the 2 data frames into one of them. Please pay attention that I want to add the entire row.

Here is an example:

# df1

customer_ip   V1  V2
   1          15  20
   2          12  18

# df2

customer_ip   V1  V2
   2          45  50
   3          12  18

And I want my new data frames to look like:

# df1

customer_ip   V1  V2
   1          15  20
   2          12  18
   2          45  50

# df2

customer_ip   V1  V2

   3          12  18

Thank you in advance!

Upvotes: 0

Views: 2130

Answers (2)

ekmz
ekmz

Reputation: 93

This does it.

df1<-rbind(df1,df2[df2$customer_ip %in% df1$customer_ip,])

df2<-df2[!(df2$customer_ip %in% df1$customer_ip),]

EDIT: Gaurav & Sotos got here before me whilst I was writing with essentially the same answer, but I'll leave this here as it shows the code without the redundant 'which'

Upvotes: 3

Gaurav Bansal
Gaurav Bansal

Reputation: 5660

This should do the trick:

#Add appropriate rows to df1
df1 <- rbind(df1, df2[which(df2$customer_ip %in% df1$customer_ip),])

#Remove appropriate rows from df2
df2 <- df2[-which(df2$customer_ip %in% df1$customer_ip),]

Upvotes: 2

Related Questions