Calculate ages in R

前端 未结 8 1756
北荒
北荒 2020-11-27 16:39

I have two data frames in R. One frame has a persons year of birth:

YEAR
/1931
/1924

and then another column shows a more recent time.

相关标签:
8条回答
  • 2020-11-27 17:29

    I think this might be a bit more intuitive and requires no formatting or stripping:

    as.numeric(as.Date("2002-02-02") - as.Date("1924-08-03")) / 365
    

    gives output:

    77.55342
    

    Then you can use floor(), round(), or ceiling() to round to a whole number.

    0 讨论(0)
  • 2020-11-27 17:34

    Based on the previous answer, convert your columns to date objects and subtract. Some conversion of types between character and numeric is necessary:

    > foo=data.frame(RECENT=c("09/08/2005","11/08/2005"),YEAR=c("/1931","/1924"))
    > foo
          RECENT  YEAR
    1 09/08/2005 /1931
    2 11/08/2005 /1924
    > foo$RECENTd = as.Date(foo$RECENT, format="%m/%d/%Y")
    > foo$YEARn = as.numeric(substr(foo$YEAR,2,999))
    > foo$AGE = as.numeric(format(foo$RECENTd,"%Y")) - foo$YEARn
    > foo
          RECENT  YEAR    RECENTd YEARn AGE
    1 09/08/2005 /1931 2005-09-08  1931  74
    2 11/08/2005 /1924 2005-11-08  1924  81
    

    Note I've assumed you have that slash in your year column.

    Also, tip for when asking questions about dates is to include a day that is past the twelfth so we know if you are a month/day/year person or a day/month/year person.

    0 讨论(0)
提交回复
热议问题