Search code examples
rdataframerbind

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.


Solution

  • We get the index of duplicated elements and use that to filter

    rbind(df2, df1)[!duplicated(c(row.names(df2), row.names(df1))),]