merge/combine columns with same name but incomplete data

后端 未结 7 982
臣服心动
臣服心动 2020-12-14 17:57

I have two data frames that have some columns with the same names and others with different names. The data frames look something like this:

df1
      ID hel         


        
7条回答
  •  难免孤独
    2020-12-14 18:12

    Here's an approach that involves melting your data, merging the molten data, and using dcast to get it back to a wide form. I've added comments to help understand what is going on.

    ## Required packages
    library(data.table)
    library(reshape2)
    
    dcast.data.table(
      merge(
        ## melt the first data.frame and set the key as ID and variable
        setkey(melt(as.data.table(df1), id.vars = "ID"), ID, variable), 
        ## melt the second data.frame
        melt(as.data.table(df2), id.vars = "ID"), 
        ## you'll have 2 value columns...
        all = TRUE)[, value := ifelse(
          ## ... combine them into 1 with ifelse
          is.na(value.x), value.y, value.x)], 
      ## This is your reshaping formula
      ID ~ variable, value.var = "value")
    #    ID hello world football baseball hockey soccer
    # 1:  1     2     3       43        6      7      4
    # 2:  2     5     1       24       32      2      5
    # 3:  3    10     8        2       23      8     23
    # 4:  4     4    17        5       15      5     12
    # 5:  5     9     7       12       23      3     43
    

提交回复
热议问题