我其实很喜欢cut 方法。
d |>
transform(date_s=cut(as.POSIXct(d$Date), breaks="3 hours")) |>
with(aggregate(list(mn_temp=temp), list(date=date_s, ID=ID), FUN=mean))
# date ID mn_temp
# 1 2012-01-01 00:00:00 1155 -0.06666667
# 2 2012-01-01 03:00:00 1155 0.56666667
# 3 2012-01-01 06:00:00 1155 0.93333333
# 4 2012-01-01 09:00:00 1155 3.70000000
如果我们想要显示时间间隔的结束而不是开始时间,我们可以这样做
d |>
transform(date_s=cut(
as.POSIXct(d$Date), breaks="3 hours",
labels=(as.POSIXct(Date) + 10800)[(seq(Date) - 1) %% 3 == 0])) |>
with(aggregate(list(mn_temp_lst3=temp), list(date=date_s, ID=ID), FUN=mean))
# date ID mn_temp_lst3
# 1 2012-01-01 03:00:00 1155 -0.06666667
# 2 2012-01-01 06:00:00 1155 0.56666667
# 3 2012-01-01 09:00:00 1155 0.93333333
# 4 2012-01-01 12:00:00 1155 3.70000000
数据
d <- structure(list(ID = c(1155L, 1155L, 1155L, 1155L, 1155L, 1155L,
1155L, 1155L, 1155L, 1155L), Date = c("2012-01-01 00:00:00",
"2012-01-01 01:00:00", "2012-01-01 02:00:00", "2012-01-01 03:00:00",
"2012-01-01 04:00:00", "2012-01-01 05:00:00", "2012-01-01 06:00:00",
"2012-01-01 07:00:00", "2012-01-01 08:00:00", "2012-01-01 09:00:00"
), temp = c(-0.8, 0.1, 0.5, 0.6, 0.6, 0.5, 0.7, 0.9, 1.2, 3.7
)), row.names = c(NA, -10L), class = "data.frame")