David
David

Reputation: 21

Using R, calculate Date of Birth by subtracting age (in years to 2SD) from an event

I have a dataframe that gives me each unique individuals age in years (to 2 decimal places) on the date of an event:

id                eventDate              ageatEvent
1                 10-Jun-90                  44.07
2                 15-Feb-91                  30.45
3                 20-Dec-93                  59.43
4                 13-Nov-93                  45.84
5                 26-Jul-95                  25.94
6                 10-Mar-99                  21.97
7                 20-Jun-05                  32.28
8                 31-Jan-96                  48.82

Using R, I would like to calculate each individual's date of birth (as precise as is possible given the data). I have tried using lubridate but it is unclear what I should be converting the numeric 'age' column into, in order to subtract from the POSIXct instant eventDate.

Many thanks in advance for any assistance.

Upvotes: 2

Views: 220

Answers (1)

Flo.P
Flo.P

Reputation: 371

You can do that with lubridate package.

dmy converts characters to date using the order day-month-year. dyearconverts numeric to duration in years.

The difference gives the result.

library(tidyverse)
library(lubridate)

df  <- tribble( 
~id, ~eventDate, ~ageatEvent,
1, "10-Jun-90", 44.07,

2, "15-Feb-91", 30.45,

3, "20-Dec-93", 59.43)

df <- df %>%  
  mutate(eventDate = dmy(eventDate), ageatEvent = dyears(ageatEvent)) %>% 
  mutate(dateOfBirth = eventDate - ageatEvent)

Upvotes: 2

Related Questions