How do I convert date to number of days in R

后端 未结 7 1696
囚心锁ツ
囚心锁ツ 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条回答
  •  Happy的楠姐
    2021-01-04 15:01

    Assuming that you wish to count January 1 of the year as 0 we get:

    DF <- data.frame(Date = c("02/01/2000", "20/02/2000", "12/12/2000", "13/01/2001"))
    DF$Date <- as.Date(DF$Date, "%d/%m/%Y")
    
    Diff <- function(x, start) as.numeric(x - as.Date(cut(start, "year")))
    transform(DF, NumDays = Diff(Date, Date), TotalDays = Diff(Date, Date[1]))
    

    which gives;

            Date NumDays TotalDays
    1 2000-01-02       1         1
    2 2000-02-20      50        50
    3 2000-12-12     346       346
    4 2001-01-13      12       378
    

    If you want to count January 1st as 1 then add 1 to the expression in Diff.

    UPDATE: Correction.

    UPDATE: Added DFdefinition to make it self contained.

    UPDATE: We add a run using data in comment below.

    > DF <- data.frame(Date = as.Date(c("1980-01-03", "1980-01-04", "1980-01-05", 
    + "1980-01-07", "1980-01-10", "1980-01-16")))
    > 
    > Diff <- function(x, start) as.numeric(x - as.Date(cut(start, "year")))
    > transform(DF, NumDays = Diff(Date, Date), TotalDays = Diff(Date, Date[1]))
            Date NumDays TotalDays
    1 1980-01-03       2         2
    2 1980-01-04       3         3
    3 1980-01-05       4         4
    4 1980-01-07       6         6
    5 1980-01-10       9         9
    6 1980-01-16      15        15
    

提交回复
热议问题