install.packages(c("tidyverse", "here", "tsibble", "lubridate", "DAAG", "broom", "patchwork", "colorspace", "GGally", "tsibbledata", "forcats", "chron", "sugrrants"))
::install_github("njtierney/brolgar")
remotes::install_github("hrbrmstr/streamgraph") remotes
ETC5521 Tutorial 10
Exploring data having a space and time context
🎯 Objectives
These exercise are to do some exploratory analysis with graphics and statistical models, focusing on temporal data analysis.
🔧 Preparation
- The reading for this week is Reintroducing tsibble: data tools that melt the clock and brolgar: An R package to BRowse Over Longitudinal Data Graphically and Analytically in R.
- Complete the weekly quiz, before the deadline!
- Install the following R-packages if you do not have them already:
- Open your RStudio Project for this unit, (the one you created in week 1,
eda
orETC5521
).
Exercise 1: Australian rain
This exercise is based on one from Unwin (2015), and uses the bomregions
data from the DAAG
package. The data contains regional rainfall for the years 1900-2008. The regional rainfall numbers are area-weighted averages for the respective regions. Extract just the rainfall columns from the data, along with year.
- What do you think area-weighted averages are, and how would these be calculated?
- Make line plots of the rainfall for each of the 7 regions and the Australian averages. What do you learn about rainfall patterns across the years and regions? (Hint: you can make these with the
ggduo
function in theGGally
package.)
- It can be difficult to assess correlation between multiple series using line plots, and the best way to check correlation between multiple series is to make a scatterplot. Make a splom for this data, ignoring year. What regions have strong positive correlation between their rainfall averages?
- One of the consequences of climate change for Australia is that some regions are likely getting drier. Make a transformation of the data to compute the difference between rainfall average in the year, and the mean over all years. Using a bar for each year, make a barchart that examines the differences in the yearly rainfall over time. (Hint: you will need to pivot the data into tidy long form to make this easier.) Are there some regions who have negative differences in recent years? What else do you notice?
Exercise 2: US unemployment
This exercise is based on and example in Oscar Perpinan Lamigueiro (2018) “Displaying Time Series, Spatial, and Space-Time Data with R”. Read the US employment data from the book web site. This contains monthly unemployment numbers from 2000 through 2012 in different sectors.
- Transform the data into tidy long form and convert to a
tsibble
. Make a line plot coloured by sector. What do you learn about unemployment during this time frame from this chart?
- We are going to re-arrange the data now to examine the monthly patterns by year and sector. Create new variables for month and year from the date variable. Now make a line plot of count by month coloured by year, using an appropriately sequential colour palette, and facet by sector. Are there some sectors that have a seasonal pattern? Are there some sectors who were not affected by the 2008 economic downfall?
- This next way to look at the data is like a stacked bar chart for time series. Using the same code as in question a., change
geom_line
withgeom_area
, to stack the series, with a different fill colour for each sector. What do you learn about the magnitude of the 2008 economic crisis? Can you read much from this chart about the effect on different sectors?
Exercise 3: Lynx trappings periodicity
The lynx
data in R is a classic example: Annual numbers of lynx trappings for 1821–1934 in Canada, from Brockwell & Davis (1991). It is a classic because it looks periodic, but it really doesn’t have a period. Here we look at two ways to examine the cyclic nature to check for periodicity.
- Make a line plot of count by year. Do you agree that it looks periodic?
- Create two new variables by rounding the year into a decade, and the remainder into a year in the decade.
- Add a vertical line every 10 years, to your plot of counts over time. If you start from 1928, the location of the first peak, you can check the peak locations in subsequent years. Is the peak roughly every 10 years?
- Cut the series into decades, and make overlaid line plots of count vs year in decade, using decade as the group variable. This is like looking at seasonality, like we might look at seasonal patterns in a year by examining the months. If the series is cyclic, particularly with peaks every 10 years, the peaks should line up. Do they?
Exercise 4: Missing values in NYC bikes data
In Earo Wang’s blog post introducing tsibble
she used NYC bikes data. This data is now made available in the tsibbledata
package.
- Focusing on May, aggregate the data to hour, and count the number of trips in each hour.
- Has the data got missing values?
- Make a line plot of the hourly trips over the month. Why does it look like there are no missings? Why is the line not broken by missings?
- Use
fill_gaps
to make implicit missings explicit. Re-make the line plot from question c again.
- To focus on the missings, we can make a plot of the places where there are gaps, by plotting the data created by the
count_gaps
function. How extensive are the missing values?
- Focusing on the hour when missings occur, check if there are some times of the day that missings are more frequent.
Exercise 5: Imputing missings for pedestrian sensor using a model
We saw in the lecture notes that imputing by simple method such as mean or moving average doesn’t work well with multiple seasonality in a time series. Here we will use a linear model to capture the seasonality and produce better imputations for the pedestrian sensor data (from the tsibble
package).
- What are the multiple seasons of the pedestrian sensor data, for
QV Market-Elizabeth St (West)
? (Hint: Make a plot to check. You might filter to a single month to make it easier to see seasonality. You might also want to check when Queen Victoria Market is open.)
- Check and fill the gaps for the pedestrian sensor data with NA. Subset to just the QV market sensor.
- Create a new variable to indicate if a day is a non-working day, called
hol
. Make hour a factor - this helps to make a simple model for a non-standard daily pattern.
- Fit a linear model with Count as the response on predictors
Time
andhol
interacted.
- Predict the count for all the data at the sensor.
- Make a line plot focusing on the last two weeks in 2015, where there was a day of missings, where the missing counts are substituted by the model predictions. Do you think that these imputed values match the rest of the series, nicely?
Exercise 6: Men’s heights
The heights
data provided in the brolgar
package contains average male heights in 144 countries from 1500-1989.
- What’s the time index for this data? What is the key?
- Filter the data to keep only measurements since 1700, when there are records for many countries. Make a spaghetti plot for the values from Australia. Does it look like Australian males are getting taller?
- Check the number of observations for each country. How many countries have less than five years of measurements? Filter these countries out of the data, because we can’t study temporal trend without sufficient measurements.
- Make a spaghetti plot of all the data, with a smoother overlaid. Does it look like men are generally getting taller?
- Use
facet_strata
to break the data into subsets using theyear
, and plot is several facets. What sort of patterns are there in terms of the earliest year that a country appears in the data?
- Compute the three number summary (min, median, max) for each country. Make density plots of these statistics, overlaid in a single plot, and a parallel coordinate plot of these three statistics. What is the average minimum (median, maximum) height across countries? Are there some countries who have roughly the same minimum, median and maximum height?
- Which country has the tallest men? Which country has highest median male height? Which country has the shortest men? Would you say that the distribution of heights within a country is similar for all countries?
👋 Finishing up
Make sure you say thanks and good-bye to your tutor. This is a time to also report what you enjoyed and what you found difficult.