Search code examples
rdatedatetimedate-formattingdate-conversion

calculation of age based on any preveous time


Is there a way to find the solution of problem like this;

if my age on 10/jan/2010 was 2 year how much will be the age on 10/April/2012.

kind regards


Solution

  • Simply use difftime() to calculate the difference and then add the age. Something like this:

    earlier_age <- 2
    diff <- as.numeric(difftime(latest_date, earlier_date), units="years") 
    #make sure that dates are actually date objects (using as.Date())
    new_age <- diff + earlier_age
    
    
    #So for your example:
    latest_date <- as.Date("10/April/2012", format = "%d/%B/%Y")
    earlier_date <- as.Date("10/jan/2010", format = "%d/%b/%Y")
    earlier_age <- 2
    
    diff <- as.numeric(difftime(latest_date, earlier_date), units="days")/365.25
    new_age <- diff + earlier_age
    

    You can change the units to weeks, hours and so on as per your requirement