Calculate ages in R

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

    You can solve this with the lubridate package.

    > library(lubridate)
    

    I don't think /1931 is a common date class. So I'll assume all the entries are character strings.

    > RECENT <- data.frame(recent = c("09/08/2005", "11/08/2005"))
    > YEAR <- data.frame(year = c("/1931", "/1924"))
    

    First, let's notify R that the recent dates are dates. I'll assume the dates are in month/day/year order, so I use mdy(). If they're in day/month/year order just use dmy().

    > RECENT$recent <- mdy(RECENT$recent)
          recent
    1 2005-09-08
    2 2005-11-08
    

    Now, lets turn the years into numbers so we can do some math with them.

    > YEAR$year <- as.numeric(substr(YEAR$year, 2, 5))
    

    Now just do the math. year() extracts the year value of the RECENT dates.

    > year(RECENT$recent) - YEAR
      year
    1   74
    2   81
    

    p.s. if your year entries are actually full dates, you can get the difference in years with

    > YEAR1 <- data.frame(year = mdy("01/08/1931","01/08/1924"))
    > as.period(RECENT$recent - YEAR1$year, units = "year")
    [1] 74 years and 8 months   81 years and 10 months
    

提交回复
热议问题