R: Updating a data frame with another data frame

后端 未结 4 1130
别那么骄傲
别那么骄傲 2020-12-18 12:51

Let\'s say our initial data frame looks like this:

df1 = data.frame(Index=c(1:6),A=c(1:6),B=c(1,2,3,NA,NA,NA),C=c(1,2,3,NA,NA,NA))

> df1
  Index A  B  C
         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 13:03

    merge then aggregate:

    aggregate(. ~ Index, data=merge(df1, df2, all=TRUE), na.omit, na.action=na.pass )
    
    #  Index B C A
    #1     1 1 1 1
    #2     2 2 2 2
    #3     3 3 3 3
    #4     4 4 5 4
    #5     5 4 5 5
    #6     6 4 5 6
    

    Or in dplyr speak:

    df1 %>% 
        full_join(df2) %>%
        group_by(Index) %>%
        summarise_each(funs(na.omit))
    
    #Joining by: c("Index", "B", "C")
    #Source: local data frame [6 x 4]
    #
    #  Index     A     B     C
    #  (dbl) (int) (dbl) (dbl)
    #1     1     1     1     1
    #2     2     2     2     2
    #3     3     3     3     3
    #4     4     4     4     5
    #5     5     5     4     5
    #6     6     6     4     5
    

提交回复
热议问题