3
library(plyr)
library(dplyr)
library(lubridate)

d.in <- read.csv("C:/Users/Person/Documents/dataset.csv")
d.in <- mutate(d.in, dob=mdy(dob))
summary(d.in$dob)

d.in <- mutate(d.in, dob = mdy(dob), hosp_admission = mdy(hosp_admission))
d.in <- mutate(d.in, age_at_admission = 
interval(dob,hosp_admission)/dyears(1))

Using this code I get the following message: Warning message: All formats failed to parse. No formats found.

Also, it's changes all of my dates of birth and age at admission to N/A.

DTYK
  • 1,098
  • 1
  • 8
  • 33
V. van Wei
  • 41
  • 1
  • 2
  • 1
    Welcome to SO. Please add a bit of data via `dput(head(d.in))`. We cannot reproduce your errors without a data example. Read the SO post on [how to create a reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and follow the SO tour. – phiver Jun 26 '18 at 11:54

3 Answers3

4

This seems the most straight-forward to me using the example data from another answer:

d.in <- data.frame(
    dob = c("01-30-1978", "02-10-1960", "03-04-1990"),
    hosp_admission = c("12-20-2015", "06-15-2000", "07-06-2017"))


d.in %>%
    mutate(
        dob = mdy(dob),
        hosp_admission = mdy(hosp_admission),
        age = year(hosp_admission) - year(dob))

dob hosp_admission age
1 1978-01-30     2015-12-20  37
2 1960-02-10     2000-06-15  40
3 1990-03-04     2017-07-06  27
GISHuman
  • 1,026
  • 1
  • 8
  • 27
3

In lubridate we can use decimal_year with floor

# Generate some sample data
d.in <- data.frame(
    dob = c("01-30-1978", "02-10-1960", "03-04-1990"),
    hosp_admission = c("12-20-2015", "06-15-2000", "07-06-2017"))

library(lubridate);
library(tidyverse);
    d.in %>%
        mutate(
            dob = mdy(dob),
            hosp_admission = mdy(hosp_admission),
            age = floor(decimal_date(hosp_admission) - decimal_date(dob)))
#         dob hosp_admission age
#1 1978-01-30     2015-12-20  37
#2 1960-02-10     2000-06-15  40
#3 1990-03-04     2017-07-06  27
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
0

Not sure if the requirement is to use lubridate but the function age in the MESS package computes the age (in years) between two dates:

born <- c("1971-08-18", "2000-02-28", "2001-12-20")
check <- c("2018-06-26")
MESS::age(born, check)

which returns

[1] 46 16 14
ekstroem
  • 5,957
  • 3
  • 22
  • 48