4

I'm trying to determine the number of months between baseline and followup my date looks like this

-------------------------
|  Baseline | Follow_Up  |
-------------------------
|  10/6/15  | 10/10/17   |
|  10/6/15  | 4/20/18    |
|  10/6/15  | 4/18/18    |
|  10/6/15  | 7/2/18     |
|  10/6/15  | 8/8/17     |
|  10/6/15  | 1/17/18    |
|  10/6/15  | 10/19/17   |
--------------------------

And I looking for output as this

---------------------------------------------
|  Baseline | Follow_Up  | Months difference|
---------------------------------------------
|  10/6/15  | 10/10/17   |24.5              |
|  10/6/15  | 4/20/18    |30.9              |
|  10/6/15  | 4/18/18    |30.8              |
|  10/6/15  | 7/2/18     |33.3              |
|  10/6/15  | 8/8/17     |22.4              |
|  10/6/15  | 1/17/18    |27.8              | 
|  10/6/15  | 10/19/17   |24.8              |
---------------------------------------------

I would like to know which package can I use to do this calculation

Thank you

Mr.M
  • 111
  • 1
  • 9
  • Does this answer your question? [Number of months between two dates](https://stackoverflow.com/questions/1995933/number-of-months-between-two-dates) – anotherfred Nov 24 '19 at 20:30
  • Does this answer your question? [Get the difference between dates in terms of weeks, months, quarters, and years](https://stackoverflow.com/questions/14454476/get-the-difference-between-dates-in-terms-of-weeks-months-quarters-and-years) – camille Nov 25 '19 at 03:38

2 Answers2

13

Here is an option with lubridate

library(dplyr)
library(lubridate)
df1 %>%
      mutate(Months_difference = (interval(mdy(Baseline), 
             mdy(Follow_Up))) %/% months(1))
akrun
  • 874,273
  • 37
  • 540
  • 662
-1

Using base R, we can convert the data into "Date" object and then use difftime to calculate the difference between the two columns.

df[] <- lapply(df, as.Date, "%m/%d/%y")
df$Month_diff <- as.numeric(difftime(df$Follow_Up, df$Baseline, units = "days")/30)
df

#    Baseline  Follow_Up Month_diff
#1 2015-10-06 2017-10-10       24.5
#2 2015-10-06 2018-04-20       30.9
#3 2015-10-06 2018-04-18       30.8
#4 2015-10-06 2018-07-02       33.3
#5 2015-10-06 2017-08-08       22.4
#6 2015-10-06 2018-01-17       27.8
#7 2015-10-06 2017-10-19       24.8

data

df <- structure(list(Baseline = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
1L), .Label = "10/6/15", class = "factor"), Follow_Up = structure(c(2L, 
5L, 4L, 6L, 7L, 1L, 3L), .Label = c("1/17/18", "10/10/17", "10/19/17", 
"4/18/18", "4/20/18", "7/2/18", "8/8/17"), class = "factor")), 
class = "data.frame", row.names = c(NA, -7L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    This just hardcodes each month as having 30 days... a quick recipe for disaster – Cos Mar 15 '22 at 10:19