通过在 R 中添加句点 class 对象和 lubridate 来计算以年和月为单位的年龄

Calculate age in years and months by adding period class objects together with lubridate in R

我的数据有一个基线年龄变量,以及一个自基线观察以来的月数的后续变量。两者都是只有整数的数值向量。我想计算跟进时的年龄。当我使用 lubridate 将这些变量解析为周期对象并将它们加在一起时,我得到的结果类似于 5 年 14 个月。理想情况下 - 我希望这是 6 年 2 个月。

示例

library(dplyr)
library(lubridate)
library(magrittr)

set.seed(080617)
df <- 
  tibble(year = sample(20),
     month = sample(20))

df %<>% 
  mutate(year = years(year)) %>% 
  mutate(month = months(month)) %>%
  mutate(age = (year + month))
df

我试过使用 df$age <- as.period(df$age, units = "years") 无济于事。

有什么建议吗?

这应该可以为您提供所需的结果。我将列名更改为 year.col 和 month.col,以便更容易遵循逻辑

library(dplyr)
library(lubridate)
library(magrittr)

set.seed(080617)
df <- 
  tibble(year.col = sample(20),
         month.col = sample(20))

df %<>% 
  mutate(year.col = years(year.col)) %>% 
  mutate(month.col = months(month.col)) %>%
  mutate(age = year.col + years(month(month.col) %/% 12) + months(month(month.col) %% 12))