If you are able to create a data.frame that has date and temperature columns, similar to my dummy dataset below, you can easily use the dplyr and lubridate packages to get monthly and yearly means.
Add Month and Year Columns to df using dplyr's mutate function and lubridates month and year functions
library(lubridate)
library(dplyr)
df <- data.frame(date = seq(from = ymd("2017-01-01"), to = ymd("2018-12-31"), length.out = 730),
temp = rnorm(n = 730, mean = 23, sd = 12))
Add Month and Year Columns to df using dplyr's mutate function and lubridate's month and year functions
df <- df %>% mutate(Month = month(date), Year = year(date))
The first six rows of df:
# date temp Month Year
# 2017-01-01 17.13885 1 2017
# 2017-01-02 34.23553 1 2017
# 2017-01-03 10.25110 1 2017
# 2017-01-04 11.19415 1 2017
# 2017-01-05 28.09097 1 2017
# 2017-01-06 17.58424 1 2017
You can get the monthly means using dplyr's group_by function, to group the data.frame by month and year, and the summarise function to calculate the means.
monthly_summaries <- df %>% group_by(Year, Month) %>%
summarise(mean_temp = mean(temp))
Here's the first 6 rows of the monthly_summaries data.frame
# Year Month mean_temp
# 2017 1 22.1
# 2017 2 24.6
# 2017 3 20.5
# 2017 4 25.7
# 2017 5 21.3
# 2017 6 23.4
Similarly, to get the yearly means, using the group_by function to group by year, and the summarise function to calculate the yearly means.
yearly_summaries <- df %>% group_by(Year) %>%
summarise(mean_temp = mean(temp))
And here's the yearly summaries data.frame:
#Year mean_temp
# 2017 23.0
# 2018 23.1
(alternatively, if you don't want to add Month and Year columns to your data.frame, you could get the same output using the following code:
monthly_summaries <- df %>% group_by(Year = year(date), Month = month(date)) %>%
summarise(mean = mean(temp))
yearly_summaries <- df %>% group_by(Month = month(date)) %>%
summarise(mean = mean(temp))
)
dputto get alternative approaches independent of these packages(if possible)?dput(head(df,20))dput