collapse mulitple columns into one column and generate an index variable

后端 未结 4 939
误落风尘
误落风尘 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条回答
  •  离开以前
    2021-01-22 09:25

    This is a classic use of reshape to go from "wide" to "long" format. If d is your data.frame:

    d2 <- reshape(d, idvar = "Id", v.names = "Date", timevar = "Index",
                  varying = c("Date1", "Date2", "Date3"), direction = "long")
    

    Result:

    > d2
         Id Index       Date
    12.1 12     1 2005-12-22
    11.1 11     1 2009-10-11
    29.1 29     1       
    45.1 45     1       
    39.1 39     1       
    44.1 44     1       
    12.2 12     2       
    11.2 11     2       
    29.2 29     2 2005-04-11
    45.2 45     2       
    39.2 39     2       
    44.2 44     2 2005-04-16
    12.3 12     3       
    11.3 11     3       
    29.3 29     3       
    45.3 45     3 2008-11-06
    39.3 39     3 2006-01-02
    44.3 44     3       
    

    If you don't want all the NA values (above) you can subset:

    > d2[!is.na(d2$Date),]
         Id Index       Date
    12.1 12     1 2005-12-22
    11.1 11     1 2009-10-11
    29.2 29     2 2005-04-11
    44.2 44     2 2005-04-16
    45.3 45     3 2008-11-06
    39.3 39     3 2006-01-02
    

提交回复
热议问题