How do you reduce granularity to every 4 hours in R with filter function [closed]
Solution 1:
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
dates <- c("2021-01-01 02:35:00", "2021-01-02 14:17:24", "2022-04-26 17:03:22")
for (i in 1:length(dates)) {
newDate <- date(as_datetime(dates[i]))
newHour <- floor(hour(as_datetime(dates[i])) / 4)
dateModule4 <- as_datetime(paste(newDate, paste0(newHour * 4, ":00:00"), sep = " "))
print(dateModule4)
}
#> [1] "2021-01-01 UTC"
#> [1] "2021-01-02 12:00:00 UTC"
#> [1] "2022-04-26 16:00:00 UTC"
Generally, it roundes down to floor/4 == 0
Created on 2022-01-21 by the reprex package (v2.0.1)