Generating a monthly average
While the to.period()
command is useful in many contexts, for your purposes it may not be useful to select a single row as representative of the entire month.
Instead, it makes more sense to generate average temperature values per month. To do so, you'll need to manually calculate the monthly average using split() and lapply(), then generate a new xts object using as.xts() This may seem like a complicated process, but you already have the skills to do it!
The subsetted xts object from the previous exercise, temps_xts_2
, is preloaded in your workspace. Also preloaded is an index
object containing a vector of dates for the first day of each month covered in the data.
This is a part of the course
“Case Study: Analyzing City Time Series Data in R”
Exercise instructions
- Use
split()
to generate monthly lists from themean
column of yourtemps_xts_2
object. Be sure to specify"months"
as the period (thef
argument). - Use
lapply()
to calculate the "mean of means", or the average mean temperature per month. - Use
as.xts()
to generate a new xts object containing average monthly temperature in Boston from 2010 through 2015. To do this, you will need to combine your monthlymean_of_means
data with your monthlyindex
object. - Finally, confirm that your new
temps_monthly
object shares a duration and periodicity withflights_xts
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Split temps_xts_2 into separate lists per month
monthly_split <- split(___$___ , f = "___")
# Use lapply to generate the monthly mean of mean temperatures
mean_of_means <- lapply(___, FUN = ___)
# Use as.xts to generate an xts object of average monthly temperature data
temps_monthly <- as.xts(as.numeric(___), order.by = ___)
# Compare the periodicity and duration of your new temps_monthly and flights_xts
periodicity(___)
periodicity(___)