R语言 如何创建和合并期间间隔?

ruarlubt  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(126)

我想创建一个像这样的时间间隔(0,5]月和(5,10]月。然后将这些时间间隔合并到(0,10]月。我用下面的数据框简化了我的真实的问题。

df <- data.frame(age = c(lubridate::period(c(0,1,0),c("day","month","year")), 
lubridate::period(c(0,2,0),c("day","month","year")),
lubridate::period(c(0,3,0),c("day","month","year")),
lubridate::period(c(0,4,0),c("day","month","year")),
lubridate::period(c(0,5,0),c("day","month","year")),
lubridate::period(c(0,6,0),c("day","month","year")),
lubridate::period(c(0,7,0),c("day","month","year")),
lubridate::period(c(0,8,0),c("day","month","year")),
lubridate::period(c(0,9,0),c("day","month","year")),
lubridate::period(c(0,10,0),c("day","month","year"))
))

cut(df$age,breaks = c(
  lubridate::period(c(0,0,0),c("day","month","year")),
  lubridate::period(c(0,5,0),c("day","month","year")),
  lubridate::period(c(0,10,0),c("day","month","year"))
))

截函数返回区间
我该怎么办?

v8wbuo2f

v8wbuo2f1#

您可以考虑底层的数字格式。

breaks <- c(
  lubridate::period(c(0,0,0),c("day","month","year")),
  lubridate::period(c(0,5,0),c("day","month","year")),
  lubridate::period(c(0,10,0),c("day","month","year"))
)
cut(as.numeric(df$age), as.numeric(breaks), labels=as.character(breaks)[-1])
# [1] 5m 0d 0H 0M 0S  5m 0d 0H 0M 0S  5m 0d 0H 0M 0S  5m 0d 0H 0M 0S 
# [5] 5m 0d 0H 0M 0S  10m 0d 0H 0M 0S 10m 0d 0H 0M 0S 10m 0d 0H 0M 0S
# [9] 10m 0d 0H 0M 0S 10m 0d 0H 0M 0S
# Levels: 5m 0d 0H 0M 0S 10m 0d 0H 0M 0S

相关问题