Get mean every n days of a month

48 views Asked by At

Let's say I have this dataframe df

day time temperature
2022/01/01 00:00:00 23
2022/01/01 06:00:00 14
2022/01/01 12:00:00 21
2022/01/01 18:00:00 13
2022/02/01 00:00:00 25
2022/02/01 06:00:00 23
2022/02/01 12:00:00 15
2022/02/01 18:00:00 17

and so on until August 31st. I would like to get everyday mean temperature but with a step of two measurements. Hence, I want to know mean temperature of timepoint 1 and 2 of the same day (and so, in this case, two means per day: one from 00:00:00 to 06:00:00 and one from 12:00:00 to 18:00:00 of every day). Actually my df is not that clean and timestamps aren't every 6 hours exact; that's why I need the most general code possible. What can I do?

1

There are 1 answers

0
HoelR On

This should ignore the irregularities in your data and take the average of the temperature recordings.

library(tidyverse)
library(lubridate)

df %>%
  group_by(day, 
           group = case_when(
    hms(time) >= hms("00:00:00") &
    hms(time) <= hms("06:00:00") ~ "early",
    TRUE ~ "late"
  )) %>% 
  summarise(
    avg_temperature = mean(temperature, na.rm = TRUE), 
    .groups = "drop") %>% 
  pivot_wider(names_from = group, values_from = avg_temperature)

# A tibble: 2 × 3
  day        early  late
  <date>     <dbl> <dbl>
1 2022-01-01  18.5    17
2 2022-02-01  24      16