rtime-seriesdata-management

Coding the number of days before and after a specific date in R


I am working with a time series data in R. I want to code the number of days before and after a specific date.

Here is an example data frame I'm working on:

df <- data.frame(date = sample(seq(as.Date("2014-01-01", "%Y-%m-%d"), by = "day", length.out = 200), 5000, replace = T))
df$Treatment[df$date <= "2014-04-02"] <- 0
df$Treatment[df$date > "2014-04-02"] <- 1

df <- df[order(df$date),]

I would like day 0 to be 2014-04-02.

Then, have it count 1,2...n every day after 2014-04-02 and then I would like it count -1, -2... -n, every day before 2014-04-02.

Such that, 2014-04-01 would be coded -1 and 2014-04-03 would be coded as 1, so on and so forth.

How can I do this efficiently in R?

Thank you!


Solution

  • Found the Answer

    This should do it.

    difftime(df$date, "2014-04-02", units = "days")
    

    You can check the results here.

    #Time Since
    df$Time_Since <- as.numeric(round(difftime(df$date, "2014-04-02", units = "days")))
    
    Check.1 <- unique(with(df, data.frame(date, Time_Since)))
    Check.2 <- Check.1[order(Check.1$date),]