我有如下指定的时间段。我有不同时间单位(年、月、周、天(的年龄,但我想添加不同的时间单位,给我一个总年龄。我的问题是,当我试图转换时间单位时,我在R中发现的函数将年作为特定的年份,将月作为特定的月份,而不是年份或月份。
你能告诉我如何添加吗,比如说,68岁到5个月到3天2小时等等。换句话说,创建一个以年为单位的列,然后我可以很容易地将其转换为以月为单位的总年龄,等等?
> head(KimAge)
# A tibble: 6 x 7
ID Years Months Weeks Days Hours
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 68 5 NA NA NA
2 2 70 2 NA NA NA
3 3 NA NA NA NA NA
4 4 23 NA NA NA NA
5 5 NA NA NA 3 NA
6 6 NA NA NA NA NA
在一些伪代码中,我试图写一些类似下面的伪代码的东西
KimAge$TotalAge = as.Year(Years) + as.month(Months) + as.week(Weeks) + as.days(Days) + as.hour(Hours)
要创建总年龄列,可以使用lubridate库:
library(dplyr)
library(lubridate)
KimAge <- tibble(years = c(68, 70, NA, 23, NA, NA),
months = c(5, 2, NA, NA, NA, NA),
weeks = c(NA, NA, NA, NA, NA, NA),
days = c(NA, NA, NA, NA, 3, NA),
hours = c(NA, NA, NA, NA, NA, NA))
# convert NA to zero
KimAge[is.na(KimAge)] <- 0
# time to duration
KimAge$TotalAge <- duration(year = KimAge$years,
month = KimAge$months,
week = KimAge$weeks,
day = KimAge$days,
hour = KimAge$hours)
如果你知道出生日期和死亡日期:
KimAge <- tibble(birth = c("1974/03/21 12:40",
"2004/9/2 00:10",
"2014/12/12 00:00",
"2012/2/1 0:0"),
death = c("2020/03/11 16:40",
"2020/7/2 14:00",
"2021/1/4 23:01",
"2012/3/2 0:0"))
KimAge$birth <- parse_date_time(KimAge$birth, "ymd H:M")
KimAge$death <- parse_date_time(KimAge$death, "ymd H:M")
KimAge$TotalAge_d <- as.duration(KimAge$death - KimAge$birth)
KimAge$TotalAge_i <- as.interval(KimAge$birth , KimAge$death)
# interval version
KimAge$years = KimAge$TotalAge_i %/% years(1)
KimAge$months = KimAge$TotalAge_i %% years(1) %/%months(1)
KimAge$days = KimAge$TotalAge_i %% years(1) %% months(1) %/% days(1)
有关lubridate的更多信息https://lubridate.tidyverse.org/.读取lubridate::period((和lubridate::interval((之间的差异。