Home > Net >  add column age from column birthdate in R
add column age from column birthdate in R

Time:12-03

Name Date
A 1990-10-7
B 1997-11-20

and i want to add column age the convert the date to the age

i try this

data$age <- age_calc(as.Date(data$dob, "%Y/%m/%d"), units = "years")

but i got this error

Error in if (any(enddate < dob)) { : 
  missing value where TRUE/FALSE needed

CodePudding user response:

The error is in the format you are giving to as.Date function

> df$age <- age_calc(as.Date(df$Date, "%Y-%m-%d"), units = "years")
> df
  Name       Date      age
1    A  1990-10-7 32.15342
2    B 1997-11-20 25.03288

Note that your Date variable use - as separator instead of / so you have to use - inside as.Date

CodePudding user response:

I recommend installing and calling the lubridate package.

Then:

data$age <- trunc((data$Date %--% today()) / years(1))

CodePudding user response:

It looks like the age_calc() function is expecting a dob (date of birth) and an enddate (end date) argument, but it's not receiving both. This is likely why you're seeing the error message about a missing value.

To fix this, you'll need to make sure that both the dob and enddate arguments are provided to the age_calc() function. For example, you could use the following code to calculate the age of each person in your data based on their date of birth and the current date:

data$age <- age_calc(as.Date(data$dob, "%Y/%m/%d"), 
                     as.Date(Sys.Date()), units = "years")

Alternatively, you could provide a specific end date to the age_calc() function instead of using the current date. This would allow you to calculate the age of each person in your data based on a specific end date rather than the current date.

I hope this helps!

  • Related