简体   繁体   中英

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.

我将其概念化为仅将df1中尚不存在的行添加到df2中:

rbind(df2, df1[setdiff(rownames(df1), rownames(df2)), ])

我们得到duplicated元素的索引,并用它来filter

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

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