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

时间:2017-01-18 08:16:38

标签: r dplyr lubridate

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

如果我使用lubridate,我会在Efficient and accurate age calculation (in years, months, or weeks) in R given birth date and an arbitrary date

中运行以下内容

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

但是,当我尝试在mutate中使用dplyr创建新变量时,我遇到了错误。

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)

它出错了:

  

mutate_impl(.data,dots)中的错误:无效的下标类型'closure'

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

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

它也会出错:

  

mutate_impl(.data,dots)中的错误:找不到对象'age'

3 个答案:

答案 0 :(得分:5)

lubridate内,

  • Period是一个S4类,有一个插槽&#34;年&#34;
  • year是一个S3类对象,其中包含从句点对象中提取年份插槽的方法。

参见https://github.com/hadley/lubridate/blob/master/R/accessors-year.r)一个访问器函数来提取年份组件。

因此,以下内容将起作用

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

答案 1 :(得分:4)

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

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

答案 2 :(得分:1)

我们可以使用j

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类,我们可能需要S4方法来提取它

period