Union dataframes in some way that updates rows with same row.name
Clash Royale CLAN TAG#URR8PPP
Union dataframes in some way that updates rows with same row.name
I want to do a union of two dataframes, that share some rows with same rowName. For those rows with common rowNames, I would like to take into account the second dataframe values, and not the first one's. For example :
df1 <- data.frame(col1 = c(1,2), col2 = c(2,4), row.names = c("row_1", "row_2"))
df1
# col1 col2
# row_1 1 2
# row_2 2 4
df2 <- data.frame(col1 = c(3,6), col2 = c(10,99), row.names = c("row_3", "row_2"))
df2
# col1 col2
# row_3 3 6
# row_2 10 99
The result I would like to obtain would then be :
someSpecificRBind(df1,df2, takeIntoAccount=df2)
# col1 col2
# row_1 1 2
# row_2 10 99
# row_3 3 6
The function rbind doesn't do the job, actually it updates rowNames for common ones.
2 Answers
2
We get the index of duplicated
elements and use that to filter
duplicated
filter
rbind(df2, df1)[!duplicated(c(row.names(df2), row.names(df1))),]
I would conceptualize this as only adding to df2
the rows in df1
that aren't already there:
df2
df1
rbind(df2, df1[setdiff(rownames(df1), rownames(df2)), ])
Great, it does the job too
– mhaddad
Aug 8 at 14:02
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Perfect, that's what I was looking for, thanks
– mhaddad
Aug 8 at 14:02