how to use merge() to update a table in R

前端 未结 6 703
孤独总比滥情好
孤独总比滥情好 2020-11-27 20:47

I\'m trying to figure out how to use merge() to update a database.

Here is an example. Take for example the data frame foo



        
6条回答
  •  眼角桃花
    2020-11-27 21:36

    I think the most simple way is to "mark" the value which need to be update prior to the merge.

    bar$update <- TRUE
    foo <- merge(foo, bar, by='index', all=T, suffixes=c("",".update"))
    foo[!is.na(foo$update),]$value <- foo[!is.na(foo$update),]$value.update
    foo$value.update <- NULL
    foo$update <- NULL
    

    It would be faster using 'data.table'

    library(data.table)
    foo <- as.data.table(foo)
    bar <- as.data.table(bar)
    bar[, update:=TRUE]
    foo <- merge(foo, bar, by='index', all=T, suffixes=c("",".update"))
    foo[!is.na(update),value:=value.update]
    foo[, c("value.update","update"):=NULL]
    foo
    
       index value
    1:     a   100
    2:     b   101
    3:     c   200
    4:     d   201
    

提交回复
热议问题