How do I convert date to number of days in R

后端 未结 7 1650
囚心锁ツ
囚心锁ツ 2021-01-04 14:19

How do I convert date to number of days, starting from the first day of the year.

How do I convert the following to the expected result below?

   Dat         


        
相关标签:
7条回答
  • 2021-01-04 15:13

    The %j datetime formatting flag will give you the day of the year starting at 0.

    d <- read.table(text='Date
    02/01/2000         
    20/02/2000         
    12/12/2000         
    13/01/2001', header=TRUE)
    
    d<-transform(d, NumDays=as.numeric(strftime(as.Date(Date, format='%d/%m/%Y'), '%j'))-1)
    #         Date NumDays
    # 1 02/01/2000       1
    # 2 20/02/2000      50
    # 3 12/12/2000     346
    # 4 13/01/2001      12
    

    Then to add the TotalDays, you can use cumsum with some modular arithmetic,

    transform(d, TotalDays=cumsum(c(1, ifelse(diff(NumDays) > 0, diff(NumDays), diff(NumDays) %% 365 + 1))))
    #         Date NumDays TotalDays
    # 1 02/01/2000       1         1
    # 2 20/02/2000      50        50
    # 3 12/12/2000     346       346
    # 4 13/01/2001      12       378
    

    Or use this shorter alternative.

    transform(d, TotalDays=cumsum(c(1, diff(as.Date(Date, format='%d/%m/%Y')))))
    
    0 讨论(0)
提交回复
热议问题