Reputation: 79
Hello all my df
has 3 columns and 100+ rows and looks like
PID Record_date DOB
123 25-02-2009 22-08-1944
165 20-04-2017 22-08-1944
I tried to calculate age for the PID but resulted like this
PID Record_date DOB Age
123 25-02-2009 22-08-1944 65
165 20-04-2017 22-08-1944 73
I have calculated age for the PID by the below code
df$Age <- as.numeric(df$Record_date - df$DOB)/365
df$Age <- round (df$Age, digits = 0)
My expected Result and outcome
PID Record_date DOB Age
123 25-02-2009 22-08-1944 64
165 20-04-2017 22-08-1944 72
Thanks in advance
Upvotes: 0
Views: 80
Reputation: 35669
You can create a period
object from the lubridate
package and extract information of years.
library(dplyr)
library(lubridate)
df %>%
mutate(across(c(Record_date, DOB), dmy),
Age = as.period(DOB %--% Record_date)$year)
# PID Record_date DOB Age
# 1 123 2009-02-25 1944-08-22 64
# 2 165 2017-04-20 1944-08-22 72
If you remove $year
, you can get detailed information of period:
# Age
# 64y 6m 3d 0H 0M 0S
# 72y 7m 29d 0H 0M 0S
Note: DOB %--% Record_date
is the shortcut of interval(DOB, Record_date)
.
Upvotes: 1
Reputation: 8880
additional solution
library(tidyverse)
library(lubridate)
df %>%
mutate(across(c(Record_date, DOB), dmy),
age = (Record_date - DOB) %/% dyears(1))
PID Record_date DOB age
1 123 2009-02-25 1944-08-22 64
2 165 2017-04-20 1944-08-22 72
Upvotes: 0
Reputation: 76673
Here is a base R solution.
diffyear <- function(x, y){
d <- difftime(x, y)
z <- as.integer(d)
years <- as.Date(z, origin = "0000-01-01")
format(years, "%Y")
}
df1$Record_date <- as.Date(df1$Record_date, "%d-%m-%Y")
df1$DOB <- as.Date(df1$DOB, "%d-%m-%Y")
diffyear(df1[[2]], df1[[3]])
#[1] "64" "72"
Now assign the return value to the new column.
Upvotes: 0
Reputation: 349
I use this function:
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)
}
Upvotes: 0
Reputation: 389325
If you round
the values, the numbers which you have got is correct. Perhaps, you want to floor
them?
library(dplyr)
df %>%
mutate(across(-1, as.Date, '%d-%m-%Y'),
age = as.integer(floor((Record_date - DOB)/365)))
# PID Record_date DOB age
#1 123 2009-02-25 1944-08-22 64
#2 165 2017-04-20 1944-08-22 72
data
df <- structure(list(PID = c(123L, 165L), Record_date = c("25-02-2009",
"20-04-2017"), DOB = c("22-08-1944", "22-08-1944")),
class = "data.frame", row.names = c(NA, -2L))
Upvotes: 0