Search code examples
rdataframemultiple-columns

add column age from column birthdate in R


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

Solution

  • 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