staove7 staove7 -4 years ago 145
R Question

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!

Answer Source

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),]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download