Reputation: 3
I am trying to calculate age in months and one particular date is giving me an incorrect result
See code below. For some reason when the date is March 1, 2019 the age in months is 2.9, which is incorrect, but for March 2, 2019 the function works better although I believe the result should be 4.x.
age_calc(as.Date("10/30/18",format="%m/%d/%y"),as.Date("3/1/19",format="%m/%d/%y"),units="months")
#[1] 2.960829
age_calc(as.Date("10/30/18",format="%m/%d/%y"),as.Date("3/2/19",format="%m/%d/%y"),units="months")
#[1] 3.993088
is this an error in the function? Or I am I doing something wrong? Is this an issue as February has fewer days??
Upvotes: 0
Views: 243
Reputation: 50718
This is perhaps more of an extended comment.
eeptools::age_calc
seems to calculate the age in months in an unconventional way (you can see the source code when you type age_calc
into an R terminal and hit Enter).
Perhaps a more canonical way to calculate the age between two dates in months is to simply divide the interval by the unit duration. A relevant & interesting post is Get the difference between dates in terms of weeks, months, quarters, and years.
From said post, @Gregor defined a convenient function that does something similar to eeptools::age_calc
library(lubridate)
age <- function(dob, age.day = today(), units = "years", floor = TRUE) {
calc.age = interval(dob, age.day) / duration(num = 1, units = units)
if (floor) return(as.integer(floor(calc.age)))
return(calc.age)
}
Using age
we then get
age(
as.Date("10/30/18",format="%m/%d/%y"),
as.Date("3/1/19",format="%m/%d/%y"),
units="months", floor = FALSE)
#[1] 4.010959
age(
as.Date("10/30/18",format="%m/%d/%y"),
as.Date("3/2/19",format="%m/%d/%y"),
units="months", floor = FALSE)
#[1] 4.043836
These values are consistent with values that e.g. Wolfram Alpha gives for the same dates.
Upvotes: 1