collapse mulitple columns into one column and generate an index variable

后端 未结 4 949
误落风尘
误落风尘 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:32

    You can also use tidyr with a small hack for the id:

    library(tidyr)
    
    df[is.na(df)]=''
    
    transform(unite(df, 'Date', Date1:Date3, sep=''), 
              id=ceiling(which(df[-1]!='')/nrow(df)))
    #  Id       Date id
    #1 12 2005-12-22  1
    #2 11 2009-10-11  1
    #3 29 2005-04-11  2
    #4 45 2008-11-06  2
    #5 39 2006-01-02  3
    #6 44 2005-04-16  3
    

提交回复
热议问题