使用带有 lubridate 函数的 mutate 计算年龄

Calculating age using mutate with lubridate functions

我想根据出生日期计算年龄。

如果我使用 lubridate,我会 运行 如下

as.period(new_interval(start = birthdate, end = givendate))$year

但是,当我尝试在dplyr中使用mutate创建新变量时,我运行出错了。

library(dplyr); library(lubridate)

birthdate <- ymd(c(NA, "1978-12-31", "1979-01-01", "1962-12-30"))
givendate <- ymd(c(NA, "2015-12-31", "2015-12-31", NA))

df <- data.frame(
    birthdate = birthdate,
    givendate = givendate)

下面的方法虽然给出了所有的日期和时间值,但仍然有效。即年、月、日、时、分、秒。

df<-df %>% mutate(age=as.period(interval(start = birthdate, end = givendate)))

# df
#    birthdate  givendate                  age
# 1       <NA>       <NA>                 <NA>
# 2 1978-12-31 2015-12-31   37y 0m 0d 0H 0M 0S
# 3 1979-01-01 2015-12-31 36y 11m 30d 0H 0M 0S
# 4 1962-12-30       <NA>                 <NA>

以下无效:

df<-df %>% 
       mutate(age=as.period(interval(start = birthdate, end = givendate))$year)

报错:

Error in mutate_impl(.data, dots) : invalid subscript type 'closure'

我认为可能是因为缺少值。所以,我尝试了:

df<-df %>% 
   mutate(age=as.period(interval(start = birthdate, end = givendate))) %>% 
   mutate(age=if_else(!is.na(age),age$year,age))

同样报错:

Error in mutate_impl(.data, dots) : object 'age' not found

我们可以使用do

df %>%
   mutate(age=as.period(interval(start = birthdate, end = givendate))) %>%
   do(data.frame(.[setdiff(names(.), "age")], 
       age = ifelse(!is.na(.$age), .$age$year, .$age)))
#    birthdate  givendate age
#1       <NA>       <NA>  NA
#2 1978-12-31 2015-12-31  37
#3 1979-01-01 2015-12-31  36
#4 1962-12-30       <NA>  NA

由于as.period自带periodclass,我们可能需要S4方法来提取它

df %>% 
    mutate(age=as.period(interval(start = birthdate, end = givendate))) %>%
   .$age %>%
   .@year %>%
    mutate(df, age = .)
#  birthdate  givendate age
#1       <NA>       <NA>  NA
#2 1978-12-31 2015-12-31  37
#3 1979-01-01 2015-12-31  36
#4 1962-12-30       <NA>  NA

我们可以使用 lubridate 中的 year 函数来获取两个日期之间的年差。

library(dplyr); library(lubridate)
df %>% mutate(age = year(givendate) - year(birthdate))

#   birthdate  givendate age
#1       <NA>       <NA>  NA
#2 1978-12-31 2015-12-31  37
#3 1979-01-01 2015-12-31  36
#4 1962-12-30       <NA>  NA

lubridate

  • Period 是一个带有插槽 "year"
  • 的 S4 class
  • year 是一个 S3 class 对象,具有从期间对象中提取年份槽的方法。

请参阅 https://github.com/hadley/lubridate/blob/master/R/accessors-year.r) 提取年份部分的访问器函数。

因此,以下将起作用

df %>% mutate(age = year(as.period(interval(start = birthdate, end = givendate))))