Using merge() and plotting over time
Now that you have temperature data covering the same time period (2010-2015) at the same frequency (monthly) as your flights data, you are ready to merge.
To merge xts objects by column, you can use merge(). When two xts objects share the same periodicity, merge()
is generally able to combine information into appropriate rows. Even when xts objects do not share the same periodicity, merge()
will preserve the correct time ordering of those objects across disparate periods.
In this exercise, you'll merge your two xts objects by column and generate new plots exploring how flight delays relate to temperature. temps_monthly
and flights_xts
are available in your workspace.
This exercise is part of the course
Case Study: Analyzing City Time Series Data in R
Exercise instructions
- Use
merge()
to combineflights_xts
andtemps_monthly
. Because these xts objects share periodicity, your merge command should place temperature data in the appropriate row in yourflights_xts
object. Note that the order in which you list the objects to be merged determines where the columns will appear in the merged object. To keep things consistent, insertflights_xts
first andtemps_monthly
second. - Examine the first few rows of your merged xts object (
flights_temps
) to confirm that the merge was successful. You should see the temperature data lined up with the flights data. - Use
plot.zoo()
to generate a single plot containing both thepct_delay
andtemps_monthly
columns fromflights_temps
. Be sure to subset the relevant columns and specifyplot.type
as"single"
. Leave thelty
argument as is.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Use merge to combine your flights and temperature objects
flights_temps <- merge(___, ___)
# Examine the first few rows of your combined xts object
# Use plot.zoo to plot these two columns in a single panel
plot.zoo(___[,c("___", "___")], plot.type = "___", lty = lty)
legend("topright", lty = lty, legend = labels, bg = "white")