簡體   English   中英

如何在 R 中將年齡計算為年、月和日?

[英]How do I calculate age as years, months, and days in R?

我想將年齡計算為年、月和日。

我可以用 python 的 dateutil 包來做

from dateutil.relativedelta import relativedelta
from datetime import date
rel_obj = relativedelta(date(2008,8,6),date(2004,1,1))
rel_obj.years, rel_obj.months, rel_obj.days

(4, 7, 5)

我在 R 中使用了 difftime 函數

o <- difftime(date("2008-8-6") , date("2004-1-1"))
o$ : has no attribute like relativedelta's

如何像在 python 中一樣格式化 difftime 對象?

這是一個包lubridate的解決方案,一個用於處理日期和時間的標准 R 包。

library(lubridate)
#> Loading required package: timechange
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

d1 <- as.Date("2004-1-1")
d2 <- as.Date("2008-8-6")

diffdays2ymd <- function(x, y, ...) {
  tmp <- x |>
    lubridate::interval(y) |> 
    lubridate::as.period()
  y <- lubridate::year(tmp)
  m <- lubridate::month(tmp)
  d <- lubridate::day(tmp)
  c(year = y, month = m, day = d)
}
diffdays2ymd(d1, d2)
#>  year month   day 
#>     4     7     5

創建於 2022-12-13,使用reprex v2.0.2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM