Calculate ages in R

前端 未结 8 1810
北荒
北荒 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: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.

提交回复
热议问题