How do I convert date to number of days in R

后端 未结 7 1695
囚心锁ツ
囚心锁ツ 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:05

    Load your dataset

    df <- structure(list(Date = structure(c(1L, 4L, 2L, 3L), .Label = c("02/01/2000", 
    "12/12/2000", "13/01/2001", "20/02/2000"), class = "factor"), 
        Date2 = structure(c(10958, 11007, 11303, 11335), class = "Date"), 
        NumDays = structure(c(1, 50, 346, 378), units = "days", class = "difftime")), .Names = c("Date", 
    "Date2", "NumDays"), row.names = c(NA, -4L), class = "data.frame")
    

    Format dates:

    startdate <- as.Date("01/01/2000","%d/%m/%Y")
    df$Date2 <-  as.Date(df$Date,"%d/%m/%Y")
    

    Use difftime to calculate the difference in days

    df$NumDays  <- difftime(df$Date2,startdate ,units="days")
    
    df
    
             Date      Date2  NumDays
    # 1 02/01/2000 2000-01-02   1 days
    # 2 20/02/2000 2000-02-20  50 days
    # 3 12/12/2000 2000-12-12 346 days
    # 4 13/01/2001 2001-01-13 378 days
    

提交回复
热议问题