0

I am new to R and not familiar with it. I have the following data:

     Start.Date       
 1: 2020-09-15 
 2: 2021-08-10 
 3: 2015-08-25 
 4: 2021-10-11 
 5: 2021-08-15 
 6: 2018-06-05 
 7: 2021-06-10 
 8: 2020-05-13 
 9: 2021-08-03 
10: 2017-12-25

I want to have the duration between the current date and the start date in months?

I tried the following but it didn't work:

install.packages("lubridate")
library("lubridate") 
currentDate <- Sys.Date()
StartDate <- as.Date(Mall_Data$Start.Date, format =  "%m/%d/%Y")
theduration<- interval(currentDate, StartDate) %% months(1)
Stephan
  • 2,056
  • 1
  • 9
  • 20
  • 1
    Your start date format is Year-Month-Day, therefor: `as.Date(Mall_Data$Start.Date, format = "%Y-%m-%d")` – Stephan Mar 23 '22 at 10:55

1 Answers1

1

you just have some typos and wrong formats in your code. Your date format is false and %% will not work, but %/% will do the job. Correct its here:

library(lubridate)

### worked with
Start.Date <- c("2020-09-15","2021-08-10","2015-08-25","2021-10-11","2021-08-15","2018-06-05","2021-06-10","2020-05-13","2021-08-03","2017-12-25")

### your corrected code
currentDate <- Sys.Date()
StartDate <- as.Date(Start.Date, format =  "%Y-%m-%d")
theduration <- interval(currentDate, StartDate) %/% months(1)
theduration

output is:

[1] -18  -7 -78  -5  -7 -45  -9 -22  -7 -50

I'll also refer to Number of months between two dates

Stephan
  • 2,056
  • 1
  • 9
  • 20