Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading