I am assuming you are working with only one city i.e. Hong Kong. If not, just add the city variable in group_by. Note that I have used summarise() instead of mutate(). Hope this helps.
suppressWarnings(suppressMessages(library(dplyr)))
suppressWarnings(suppressMessages(library(lubridate)))
#************
# Toy Data
#************
toy_data <- tibble(
date = seq(as.Date('2015-01-01'),as.Date('2015-06-30'),by = 1),
city = "Hong Kong",
avg_temp = rnorm(181, mean = 65, sd = 7),
) %>%
# Generate Month & Week
mutate(month = month(date, label = TRUE),
week = week(date))
head(toy_data)
#> # A tibble: 6 x 5
#> date city avg_temp month week
#> <date> <chr> <dbl> <ord> <dbl>
#> 1 2015-01-01 Hong Kong 63.8 Jan 1
#> 2 2015-01-02 Hong Kong 59.3 Jan 1
#> 3 2015-01-03 Hong Kong 59.7 Jan 1
#> 4 2015-01-04 Hong Kong 58.3 Jan 1
#> 5 2015-01-05 Hong Kong 52.1 Jan 1
#> 6 2015-01-06 Hong Kong 60.9 Jan 1
# Note: summarise() will create a new data frame
#*************
# Monthly Stat
#*************
monthly_stat <- toy_data %>%
group_by(month) %>%
summarise(
min_temp = min(avg_temp),
max_temp = max(avg_temp)
)
#> `summarise()` ungrouping output (override with `.groups` argument)
head(monthly_stat)
#> # A tibble: 6 x 3
#> month min_temp max_temp
#> <ord> <dbl> <dbl>
#> 1 Jan 51.0 79.0
#> 2 Feb 46.7 80.0
#> 3 Mar 49.9 87.3
#> 4 Apr 55.7 80.3
#> 5 May 51.9 78.0
#> 6 Jun 51.6 77.3
#*************
# Weekly Stat
#*************
weekly_stat <- toy_data %>%
group_by(week) %>%
summarise(
min_temp = min(avg_temp),
max_temp = max(avg_temp)
)
#> `summarise()` ungrouping output (override with `.groups` argument)
head(weekly_stat)
#> # A tibble: 6 x 3
#> week min_temp max_temp
#> <dbl> <dbl> <dbl>
#> 1 1 52.1 77.0
#> 2 2 60.0 71.7
#> 3 3 51.0 76.3
#> 4 4 61.4 79.0
#> 5 5 62.7 79.0
#> 6 6 57.7 80.0
Created on 2020-11-15 by the reprex package (v0.3.0)