Merge multiple variables in R

前端 未结 6 1741
闹比i
闹比i 2020-12-04 01:06

I have a dataset such that the same variable is contained in difference columns for each subject. I want to merge them to the same columns.

E.g.:, I have this dataf

6条回答
  •  时光说笑
    2020-12-04 01:15

    For the sake of completeness, here is also a data.table solution using melt() to reshape two measure variables simultaneously:

    library(data.table)
    cols <- c("DV1", "DV2")
    melt(setDT(DF), measure.vars = patterns(cols), value.name = cols, na.rm = TRUE)[
      , -"variable"]
    
       ID FACT DV1 DV2
    1:  1    A   1   3
    2:  2    B   4   3
    3:  3    C   5   5
    

    Now, the six columns have been merged to just two columns as requested by the OP.

    However, the OP has given a data.frame with the expected result where the new columns are appended to the existing columns. This can be achieved by joining above result with the original data frame:

     setDT(DF)[melt(DF, measure.vars = patterns(cols), value.name = cols, na.rm = TRUE)[
      , -"variable"], on = .(ID, FACT)]
    
       ID DV1_A DV1_B DV1_C DV2_A DV2_B DV2_C FACT DV1 DV2
    1:  1     1    NA    NA     3    NA    NA    A   1   3
    2:  2    NA     4    NA    NA     3    NA    B   4   3
    3:  3    NA    NA     5    NA    NA     5    C   5   5
    

提交回复
热议问题