Calculate ages in R

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

    You can do some formating:

    as.numeric(format(as.Date("01/01/2010", format="%m/%d/%Y"), format="%Y")) - 1930
    

    With your data:

    > yr <- c(1931, 1924)
    > recent <- c("09/08/2005", "11/08/2005")
    > as.numeric(format(as.Date(recent, format="%m/%d/%Y"), format="%Y")) - yr
    [1] 74 81
    

    Since you have your data in a data.frame (I'll assume that it's called df), it will be more like this:

    as.numeric(format(as.Date(df$recent, format="%m/%d/%Y"), format="%Y")) - df$year
    

提交回复
热议问题