通过在R中添加period类对象和lubridate,以年和月为单位计算年龄

通过在R中添加period类对象和lubridate,以年和月为单位计算年龄,r,lubridate,period,R,Lubridate,Period,我的数据有一个基线年龄变量,一个随访变量是基线观察后的月数。两者都是仅包含整数的数字向量。我想在随访时计算年龄。当我使用lubridate将这些变量解析为period对象并将它们加在一起时,我会得到5年14个月的结果。理想情况下-我希望这是6年2个月 范例 library(dplyr) library(lubridate) library(magrittr) set.seed(080617) df <- tibble(year = sample(20), month =

我的数据有一个基线年龄变量,一个随访变量是基线观察后的月数。两者都是仅包含整数的数字向量。我想在随访时计算年龄。当我使用lubridate将这些变量解析为period对象并将它们加在一起时,我会得到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
库(dplyr)
图书馆(lubridate)
图书馆(magrittr)
种子集(080617)
df%
突变(月=月(月))%>%
变异(年龄=(年+月))
df

我试过使用
df$age这应该会得到你想要的结果。我将列名更改为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))
库(dplyr)
图书馆(lubridate)
图书馆(magrittr)
种子集(080617)
df%
突变(month.col=month(month.col))%>%
变异(年龄=年.列+年(月(月.列)%/%12)+月(月(月.列)%%%12))

我建议对月份变量使用
%%/%
%%
运算符,并使用12作为基数。例如,
13%/%12
等于1,
13%%12
也等于1,这意味着它是1年零1个月。您应该能够在计算
时使用这些。以前从未见过/使用过整数除法或模-非常方便!这对于最小的示例非常有效。不幸的是,当我应用到我的实际数据时,我在as.POSIXlt.numeric(x)中得到了错误
错误:必须提供“origin”
。代码与上面相同,只更改了相关列名。有什么想法吗?事实上是我自己想出来的。我还加载了
mice
VIM
包。去掉这些,效果很好。不确定实际的冲突,但嘿-它的工作!