Given start date and month (numerical) how do I create a date column based off the start date and # of months in R

32 Views Asked by At

I have a list of ID's and a start date column for the first time these IDs generate value for example. We have the MonthDuration which should correspond to the start date. (Ex. for ID 1, the StartDate is 2024-01-01 which will always be MonthDuration equal to 1.

ID <- c("1","1","1","2","2")
StartDate <- c('2024-01-01', '2024-01-01', '2024-01-01', '2024-02-01','2024-02-01')
MonthDuration<- c("1","2","3","1","2")
Value <- c("153","203","391","444","212")

df <- data.frame(ID,StartDate,MonthDuration,Value)

ID  StartDate MonthDuration Value
 1 2024-01-01             1   153
 1 2024-01-01             2   203
 1 2024-01-01             3   391
 2 2024-02-01             1   444
 2 2024-02-01             2   212

What I want is the Date column to match the MonthDuration and StartDate to generate dates based off those 2 columns up until the max number of MonthDuration per ID.

ID  StartDate MonthDuration Value   Date
 1 2024-01-01             1   153   2024-01-01
 1 2024-01-01             2   203   2024-02-01 
 1 2024-01-01             3   391   2024-03-01
 2 2024-02-01             1   444   2024-02-01
 2 2024-02-01             2   212   2024-03-01 
1

There are 1 best solutions below

0
stefan_aus_hannover On BEST ANSWER

lubridate has a function to add or subtract months

Add months

library(lubridate)
df$Date <- as.Date(df$StartDate) %m+% months(as.numeric(df$MonthDuration) - 1)

Subtract months

library(lubridate)
df$Date <- as.Date(df$StartDate) %m-% months(as.numeric(df$MonthDuration))