collapse mulitple columns into one column and generate an index variable

后端 未结 4 1050
误落风尘
误落风尘 2021-01-22 08:45

I have three date columns as shown below

       Id Date1       Date2         Date3
       12 2005-12-22  NA            NA
       11 2009-10-11  NA            NA
         


        
4条回答
  •  萌比男神i
    2021-01-22 09:29

    You can consider melting your data.

    Here's an example:

    library(data.table)
    library(reshape2)
    melt(as.data.table(mydf), id.vars = "Id", na.rm = TRUE)
    #    Id variable      value
    # 1: 12    Date1 2005-12-22
    # 2: 11    Date1 2009-10-11
    # 3: 29    Date2 2005-04-11
    # 4: 44    Date2 2005-04-16
    # 5: 45    Date3 2008-11-06
    # 6: 39    Date3 2006-01-02
    
    ## More specific to what you want:
    melt(as.data.table(mydf), id.vars = "Id", na.rm = TRUE)[, 
      variable := sub("Date", "", variable)][]
    #    Id variable      value
    # 1: 12        1 2005-12-22
    # 2: 11        1 2009-10-11
    # 3: 29        2 2005-04-11
    # 4: 44        2 2005-04-16
    # 5: 45        3 2008-11-06
    # 6: 39        3 2006-01-02
    

提交回复
热议问题