Search code examples
rdatetime-seriesrecode

How to place dates on the same scale using a reference point


I have a set of dates for multiple years and I am wondering how to place them on the same scale using a reference point.

For example, I have the following dates:

"2018-04-15" "2018-04-30" "2018-05-06" "2018-05-12" "2018-05-13"

I want to create a separate column that counts the number of days these dates are from

"2018-11-06".

Thanks so much!


Solution

  • you can use difftime like this

    library(data.table)
    
    ## Create data
    df <- data.table(Date = c("2018-04-15", "2018-04-30", "2018-05-06", "2018-05-12", "2018-05-13"))
    reference <- "2018-11-06"
    
    ## Calculate difference in dates in days
    df <- df[,DaysFromRef := difftime(as.Date(reference), as.Date(Date), "days")]
    df
    
             Date DaysFromRef
    1: 2018-04-15    205 days
    2: 2018-04-30    190 days
    3: 2018-05-06    184 days
    4: 2018-05-12    178 days
    5: 2018-05-13    177 days
    
    ## Convert DaysFromRef column to numeric
    df$DaysFromRef <- as.numeric(df$DaysFromRef)