2
votes
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.

3
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 and follow the SO tour.phiver

3 Answers

2
votes

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
1
votes

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
0
votes

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