Skip to content
Prev 385723 / 398503 Next

aggregate semi-hourly data not 00-24 but 9-9

Hi Stefano,
If you mean from 9am on one day to 9am on the following day, you can
do a trick. Simply subtract 9hrs from each timestamp and then you want
midnight to midnight for these adjusted times, which you can get using
the method you followed.

I googled and found that lubridate::hours() can be used to add or
subtract hours from a POSIXct.

library(lubridate)

day_1 <- as.POSIXct("2020-02-19-00-00", format="%Y-%m-%d-%H-%M", tz="Etc/GMT-1")
day_2 <- as.POSIXct("2020-02-24-12-00", format="%Y-%m-%d-%H-%M", tz="Etc/GMT-1")
df1 <- data.frame(data_POSIX=seq(day_1, day_2, by="30 min"))
df1$hs <- rnorm(nrow(df1), 40, 10)
df1$diff[2:nrow(df1)] <- diff(df1$hs)

df1$data_POSIXminus9 <- df1$data_POSIX - lubridate::hours(9)
df1$dayX <- format(df1$data_POSIXminus9,"%y-%m-%d")
df2X <- aggregate(diff ~ dayX, df1, sum)
df2X

HTH,
Eric

On Mon, Sep 21, 2020 at 5:30 PM Stefano Sofia
<stefano.sofia at regione.marche.it> wrote: