-1

I am having a problem to calculate the age of all my participants.

I have the date of birth recorded only in terms of month and year (XX/XXXX) and I have the exact date when the data was recorded (XX/XX/XXXX).

I wanted to use the age_calc function from the eeptools package to calculate the age. Unfortunately, something does not work. I suspect it is because one date is exact whereas the other is not specifying the exact date.

This is what I have tried:

df$birthdate <- as.Date(df$birthdate)
df$visitdate <- as.Date(df$visitdate)
age <- age_calc(df$birthdate,enddate=df$visitdate, unit="year")

The response I get is: "Both dob and enddate must be Date class objects".

So what I am thinking is to change the birthdate to always the first day of the month in order to get it to work. Unfortunately, I don't know how to do that. Can anyone help out? Is there a better way of handling this problem?

Thanks in advance! Lukas

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
  • 1
    You need to specify the `format` argument in `as.Date(df$birthdate)` as `"%m/%Y"` You must have seen this error: "character string is not in a standard unambiguous format" – markus Feb 06 '19 at 08:57
  • Related / dupe: [Converting year and month (“yyyy-mm” format) to a date?](https://stackoverflow.com/questions/6242955/converting-year-and-month-yyyy-mm-format-to-a-date) – markus Feb 06 '19 at 09:01
  • Thanks for your fast reply Markus! I have tried specifying the format. Unfortunately, this resulted in all data points being transformed to NA without any error message. Do you know why this could have happened? – Lukas Preis Feb 06 '19 at 09:11
  • 2
    Show us an example of your data, probably it's a format problem. – RLave Feb 06 '19 at 09:14
  • It worked for the visit date which is specified as follows: "2019-01-25". It did not work for the birthdate which is specified as "1950-07". Here is the command I have used: df$brthdat <- as.Date(df$brthdat,"%Y-%m") – Lukas Preis Feb 06 '19 at 09:19
  • Since you're passing `units="year"`, use `as.Date(paste0(df$brthdat, "-01"))`, in order to get the birthdate to the same format. `paste0("1950-07", "-01")` adds the day. – RLave Feb 06 '19 at 09:30
  • It worked, you're awesome! Last question. How can I get the age to be precise. If someone is 75.8 years old I would like the number to be 75. I have tried to use precise=TRUE without any effect. Thanks so much! – Lukas Preis Feb 06 '19 at 09:40
  • Use `floor()` on the output from `age_calc()` or `precise = FALSE`. – RLave Feb 06 '19 at 10:00
  • It worked, thanks! :-) – Lukas Preis Feb 06 '19 at 10:30

1 Answers1

0

You need to use paste0() in order to add the day to the date:

as.Date(paste0(df$brthdat, "-01"))

So:

df$brthdat <- as.Date(paste0(df$brthdat, "-01"))
df$visitdate <- as.Date(df$visitdate)

library(eeptools)
age <- age_calc(df$birthdate,enddate=df$visitdate, unit="year", precise = FALSE)
RLave
  • 8,144
  • 3
  • 21
  • 37