19.3 — Monte Carlo methods

edits: — under construction —

Introduction

Statistical method that employ Monte Carlo methods use repeated random sampling to estimate properties of a frequency distribution. These distributions may be well-known, e.g., gamma-distribution, normal distribution, or t-distribution, or  . The simulation is based on generation of a set of random numbers on the open interval (0,1) — the set of real numbers between zero and one (all numbers greater than 0 and less than 1).

If the set included 0 and 1, then it would be called a closed set, i.e., the set includes the boundary points zero and one.

Markov chain Monte Carlo (MCMC) sampling approach used to solve large scale problems. The Markov chain refers to how the sample is drawn from a specified probability distribution. It can be drawn by discrete time steps (DTMC) or by a continuous process (CTMC). The Markov process is “memoryless:” predictions of future events are derived solely from their present state — the future and past states are independent.

Gibbs sampling is a common MCMC algorithm.

ccc

R code

R’s uniform generator is runif function. Examples of the samples generated over different values (100, 1000, 10000, 100000) with output displayed as histograms (Fig. 1). Note that as sample size increases, the simulated distributions resemble more and more the uniform distribution. Use set.seed() to reproduce the same set and sequence of numbers

require(RcmdrMisc)
par(mfrow = c(2, 2))
myUniformH <- data.frame(runif(100))
with(myUniformH, Hist(runif.100., scale="frequency", ylim=c(0,20), breaks="Sturges", col="red", xlab="100 samples", ylab="Count"))
myUniform1K <- data.frame(runif(1000))
with(myUniform1K, Hist(runif.1000., scale="frequency", ylim=c(0,150), breaks="Sturges", col="green", xlab="1K samples", ylab="Count"))
myUniform10K <- data.frame(runif(10000))
with(myUniform10K, Hist(runif.10000., scale="frequency", ylim=c(0,600), breaks="Sturges", col="lightblue", xlab="10K samples", ylab="Count"))
myUniform100K <- data.frame(runif(100000))
with(myUniform100K, Hist(runif.100000., scale="frequency", ylim=c(0,5000),breaks="Sturges", col="blue", xlab="100K samples", ylab="Count"))
#reset par()
dev.off()

Yes, a nice repeating function would be more elegant code, but we move on. As a suggestion, you should create one! Use sapply() or a basic for loop.

results of runinf with values from 100 to 100K.

Figure 1. Histograms of runif results with 100, 1K, 10K, and 100K numbers of values to be generated 

Looks pretty uniform. A property of random numbers is that history should not influence the future, i.e., no autocorrelation. We can check using the acf() function (Fig. 2).

par(mfrow = c(2, 2)) 
acf(myUniformH, main="100")
acf(myUniform1K, main="1K")
acf(myUniform10K, main="10K")
acf(myUniform100K, main="100K"
dev.off()

autocorrelation plots

Figure 2. Autocorrelation plots of runif results with 100, 1K, 10K, and 100K numbers of values

Correlations among points are plotted versus lag, where lag refers to the number of points between adjacent points, e.g., lag = 10 reflects the correlation among points 1 and 11, 2 and 12, and so forth. The band defined by two parallel blue dashed lines

Questions

  1. Use set.seed(123) and repeat runif(10) twice. Confirm that the two sets are different (do not set seed) or the same when set.seed is used. R hint: use function identical(x,y), where x and y are the two generated samples. This function tests whether the values and sequence of elements are the same between the two vectors.

Chapter 19 contents

17.8 – Assumptions and model diagnostics for Simple Linear Regression

Introduction

The assumptions for all linear regression:

  1. Linear model is appropriate.
    The data are well described (fit) by a linear model.
  2. Independent values of Y and equal variances.
    Although there can be more than one Y for any value of X, the Y‘s cannot be related to each other (that’s what we mean by independent). Since we allow for multiple Y‘s for each X, then we assume that the variances of the range of Y‘s are equal for each X value (this is similar to our ANOVA assumptions for equal variance by groups). Another term for equal variances is homoscedasticity.
  3. Normality.
    For each X value there is a normal distribution of Y‘s (think of doing the experiment over and over).
  4. Error
    The residuals (error) are normally distributed with a mean of zero.

Note the mnemonic device: Linear, Independent, Normal, Error or LINE.

Each of the four elements will be discussed below in the context of Model Diagnostics. These assumptions apply to how the model fits the data. There are other assumptions that, if violated, imply you should use a different method for estimating the parameters of the model.

Ordinary least squares makes the additional assumption about the quality of the independent variable that e that measurement of X is done without error. Measurement error is a fact of life in science, but the influence of error on regression differs if the error is associated with the dependent or independent variable. Measurement error in the dependent variable increases the dispersion of the residuals but will not affect the estimates of the coefficients; error associated with the independent variables, however, will affect estimates of the slope. In short, error in X leads to biased estimates of the slope.

The equivalent, but less restrictive practical application of this assumption is that the error in X is at least negligible compared to the measurements in the dependent variable.

Multiple regression makes one more assumption, about the relationship between the predictor variables (the X variables). The assumption is that there is no multicollinearity, a subject we will bring up next time (see Chapter 18).

Model diagnostics

We just reviewed how to evaluate the estimates of the coefficients of the model. Now we need to address a deeper meaning — how well the model explains the data. Consider a simple linear regression first. If Ho: b = 0 is not rejected — then the slope of the regression equation is taken to not differ from zero. We would conclude that if repeated samples were drawn from the population, on average, the regression equation would not fit the data well (lots of scatter) and it would not yield useful prediction.

However, recall that we assume that the fit is linear. One assumption we make in regression is that a line can, in fact, be used to describe the relationship between X and Y.

Here are two very different situations where the slope = 0.

Example 1. Linear Slope = 0, No relationship between X and Y

Example 2. Linear Slope = 0, A significant relationship between X and Y

But even if Ho: b = 0 is rejected (and we conclude that a linear relationship between X and Y is present), we still need to be concerned about the fit of the line to the data — the relationship may be more nonlinear than linear, for example. Here are two very different situations where the slope is not equal to 0.

Example 3. Linear Slope > 0, a linear relationship between X and Y

Example 4. Linear Slope > 0, curve-linear relationship between X and Y

How can you tell the difference? There are many regression diagnostic tests, many more than we can cover, but you can start with looking at the coefficient of determination (low R2 means low fit to the line), and we can look at the pattern of residuals plotted against the either the predicted values or the X variables (my favorite). The important points are:

  1. In linear regression, you fit a model (the slope + intercept) to the data;
  2. We want the usual hypothesis tests (are the coefficients different from zero?) and
  3. We need to check to see if the model fits the data well. Just like in our discussions of chi-square, a “perfect fit would mean that the difference between our model and the data would be zero.

Graph options

Using residual plots to diagnose regression equations

Yes, we need to test the coefficients (intercept Ho = 0; slope Ho = 0) of a regression equation, but we also must decide if a regression is an appropriate description of the data. This topic includes the use of diagnostic tests in regression. We address this question chiefly by looking at

  1. scatterplots of the independent (predictor) variable(s) vs. dependent (response) variable(s).
    what patterns appear between X and Y? Do your eyes tell you “Line”? “Curve”? “No relation”?
  2. coefficient of determination
    closer to zero than to one?
  3. patterns of residuals plotted against the X variables (other types of residual plots are used to, this is one of my favorites)

Our approach is to utilize graphics along with statistical tests designed to address the assumptions.

One typical choice is to see if there are patterns in the residual values plotted against the predictor variable. If the LINE assumptions hold for your data set, then the residuals should have a mean of zero with scatter about the mean. Deviations from LINE assumptions will show up in residual plots.

Here are examples of POSSIBLE outcomes:

A good residual plot, no obvious trends.

Figure 1. An ideal plot of residuals

Solution: Proceed! Assumptions of linear regression met.

Compare to plots of residuals that differ from the ideal.

We have a problem. Residual plot shows unequal variance (heteroskedasticity).

Figure 2. We have a problem. Residual plot shows a “funnel” shape — unequal variance (aka heteroscedasticity).

Solution. Try a transform like the log10-transform.

Residual plot shows systematic trend.

Figure 3. Problem. Residual plot shows systematic trend.

Solution. Linear model a poor fit; May be related to measurement errors for one or more predictor variables. Try adding an additional predictor variable or model the error in your general linear model.

Residual plot shows systematic trend.

Figure 4. Problem. Residual plot shows nonlinear trend.

Solution. Transform data or use more complex model

This is a good time to mention that in statistical analyses, one often needs to do multiple rounds of analyses, involving description and plots, tests of assumptions, tests of inference. With regression, in particular, we also need to decide if our model (e.g., linear equation) is a good description of the data.

Diagnostic plot examples

Return to our example.Tadpole dataset. To obtain residual plots, Rcmdr: Models → Graphs → Basic diagnostic plots yields four graphs. Graph A is

Basic diagnostic plots from R

Figure 5. Basic diagnostic plots. A: residual plot; B: Q-Q plot of residuals; C: Scale-location (aka spread-location) plot; D: leverage residual plot.

In brief, we look at plots

A, the residual plot, to see if there are trends in the residuals. We are looking for a spread of points equally above and below the mean of zero. In Figure 5 we count seven points above and six points below zero so there’s no indication of a trend in the residuals vs the fitted VO2 (Y) values.

B, the Q-Q plot is used to see if normality holds. As discussed before, if our data are more or less normally distributed, then points will fall along a straight line in a Q-Q plot.

C, the Scale- or spread-location plot is used to verify equal variances of errors.

D, Leverage plot — looks to see if an outlier has leverage on the fit of the line to the data, i.e., changes the slope. Additionally, provides location of Cook’s distance measure (dashed red lines). Cook’s distance measures the effect on the regression by removing one point at a time and then fitting a line to the data. Points outside the dashed lines have influence.

A note of caution about over-thinking with these plots. R provides a red line to track the points. However, these lines are guides, not judges. We humans are generally good at detecting patterns, but with data visualization, there is the risk of seeing patterns where none exits. In particular, recognizing randomness is not easy. If anything, we may tend to see patterns where none exist, termed apophenia. So yes, by all means look at the graphs, but do so with a plan: red line more or less horizontal? Then no pattern and the regression model is a good fit to the data.

Statistical test options

After building linear models, run statistical diagnostic tests that compliment graphics approaches. Here, simply to introduce the tests, I included the Gosner factor as potential predictor — many of these numerical diagnostics are more appropriate for models with more than one predictor variable, the subject of the next chapter.

Results for the model \dot{V} O_{2} \sim \text{Body.mass}+\text{Gosner} were:

lm(formula = VO2 ~ Body.mass + Gosner, data = frogs)

Residuals:
    Min      1Q Median    3Q    Max 
-163.12 -125.53 -20.27 83.71 228.56

Coefficients:
           Estimate Std. Error t value  Pr(>|t|) 
(Intercept) -595.37     239.87  -2.482 0.03487 * 
Body.mass    431.20     115.15   3.745 0.00459 **
Gosner[T.II]  64.96     132.83   0.489 0.63648 
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 153.4 on 9 degrees of freedom
  (1 observation deleted due to missingness)
Multiple R-squared: 0.8047, Adjusted R-squared: 0.7613 
F-statistic: 18.54 on 2 and 9 DF, p-value: 0.0006432

Question. Note the p-value for the coefficients — do we include a model with both body mass and Gosner Stage? See Chapter 18.5 – Selecting the best model

In R Commander, the diagnostic test options are available via

Rcmdr: Models → Numerical diagnostics

Variance inflation factors (VIF):  used to detect multicollinearity among the predictor variables. If correlations are present among the predictor variables, then you can’t rely on the the coefficient estimates — whether predictor A causes change in the response variable depends on whether the correlated B predictor is also included in the model. If correlation between predictor A and B, the statistical effect is increased variance associated with the error of the coefficient estimates. There are VIF for each predictor variable. A VIF of one means there is no correlation between that predictor and the other predictor variables. A VIF of 10 is taken as evidence of serious multicollinearity in the model.

R code:

vif(RegModel.2)

R output

Body.mass Gosner 
2.186347 2.186347 

round(cov2cor(vcov(RegModel.2)), 3) # Correlations of parameter estimates
         (Intercept) Body.mass Gosner[T.II]
(Intercept)    1.000    -0.958        0.558
Body.mass     -0.958     1.000       -0.737
Gosner[T.II]   0.558    -0.737        1.000

Our interpretation

The output shows a matrix of correlations; the correlation between the two predictor variables in this model was 0.558, large per our discussions in Chapter 16.1 . Not really surprising as older tadpoles (Gosner stage II), are larger tadpoles. We’ll leave the issue of multicollinearity to Chapter 18.1.

Breusch-Pagan test for heteroscedasticity… Recall that heteroscedasticity is another name for unequal variances. This tests pertains to the residuals; we used the scale (spread) location plot (C) above. The test statistic can be calculated as \chi^2 \approx nR^2. The function call is part of the car package, which we download as part of the Rcmdr package. R Commander will pop up a menu of choices for this test. For starters, accept the defaults, enter nothing, and click OK.

R code:

library(zoo, pos=16)
library(lmtest, pos=16)
bptest(VO2 ~ Body.mass + Gosner, varformula = ~ fitted.values(RegModel.2), studentize=FALSE, data=frogs)

R output

Breusch-Pagan test

data:  VO2 ~ Body.mass + Gosner
BP = 0.0040766, df = 1, p-value = 0.9491

Our interpretation

A p-value less than 5% would be interpreted as  statistically significant unequal variances among the residuals.

Durbin-Watson for autocorrelation… used to detect serial (auto)correlation among the residuals, specifically, adjacent residuals. Substantial autocorrelation can mean Type I error for one or more model coefficients. The test returns a test statistic that ranges from 0 to 4. A value at midpoint (2) suggests no autocorrelation. Default test for autocorrelation is r > 0.

R code:

dwtest(VO2 ~ Body.mass + Gosner, alternative="greater", data=frogs)

R output

Durbin-Watson test

data:  VO2 ~ Body.mass + Gosner
DW = 2.1336, p-value = 0.4657
alternative hypothesis: true autocorrelation is greater than 0

Our interpretation

The DW statistic was about 2. Per our definition, we conclude no correlations among the residuals.

RESET test for nonlinearity…  The Ramsey Regression Equation Specification Error Test is used to interpret whether or not the equation is properly specified. The idea is that fit of the equation is compared against alternative equations that account for possible nonlinear dependencies among predictor and dependent variables. The test statistic follows an F distribution.

R code:

resettest(VO2 ~ Body.mass + Gosner, power=2:3, type="regressor", data=frogs)

R output

RESET test

data:  VO2 ~ Body.mass + Gosner
RESET = 0.93401, df1 = 2, df2 = 7, p-value = 0.437

Our interpretation

Also a nonsignificant test — adding a power term to account for a nonlinear trend gained no model fit benefits, p-value much greater than 5%.

Bonferroni outlier test. Reports the Bonferroni p-values for testing each observation to see if it can be considered to be a mean-shift outlier (a method for identifying potential outlier values — each value is in turn replaced with the mean of its nearest neighbors, Lehhman et al 2020).  Compare to results of VIF. The objective of outlier and VIF tests is to verify that the regression model is stable, insensitive to potential leverage (outlier) values.

R code:

outlierTest(LinearModel.3)

R output

No Studentized residuals with Bonferroni p < 0.05
Largest |rstudent|:
  rstudent unadjusted p-value Bonferroni p
7 1.958858        0.085809              NA

Our interpretation

We ran the outlierTest() function on LinearModel.3 to check for influential outliers using Studentized residuals with Bonferroni correction.

The output shows “No Studentized residuals with Bonferroni p < 0.05”, which means no data points were statistically flagged as outliers after adjusting for multiple comparisons. The largest Studentized residual was 1.96 (point 7), with an unadjusted p-value of 0.086. Although this is the largest deviation from the regression line, it is not statistically significant. Therefore, we conclude that no single observation is exerting undue influence on the model fit, and we can be confident that our regression results are not driven by outliers.

Response transformation… The concept of transformations of data to improve adherence to statistical assumptions was introduced in Chapters 3.2, 13.1, and 15.

R code:

summary(powerTransform(LinearModel.3, family="bcPower"))

R output

bcPower Transformation to Normality 
    Est Power Rounded Pwr Wald Lwr Bnd Wald Upr Bnd
Y1     0.9987           1       0.2755       1.7218

Likelihood ratio test that transformation parameter is equal to 0
   (log transformation)
                           LRT df      pval
LR test, lambda = (0) 7.374316  1 0.0066162

Likelihood ratio test that no transformation is needed
                                LRT df    pval
LR test, lambda = (1) 0.00001289284  1 0.99714

Our interpretation

The Box-Cox analysis suggests that the response variable for LinearModel.3 can remain on its original scale. No power transformation was needed, and any standard linear regression inference is appropriate. The estimated transformation parameter was close to one, which suggests that the original response variable did not need a transformation. The LRT tests whether a log transformation (lambda = 0) would improve normality. The significant p-value, 0.0066, for the LRT indicates that a log transformation would not be the best choice, consistent with lambda ≈ 1. And last, the very high p-value, 0.99714, confirms that no transformation is necessary; the model residuals were close to normal.

Questions

  1. Write up three learning outcomes for this page. Hint: Point your favorite generative AI to this page and ask for help.
  2. Referring to Figures 1 – 4 on this page, which plot best suggests a regression line fits the data?
  3. Return to the electoral college data set and your linear models of Electoral vs. POP_2010 and POP_2019. Obtain the four basic diagnostic plots and comment on the fit of the regression line to the electoral college data.
    • residual plot
    • Q-Q plot
    • Scale-location plot
    • Leverage plot
  4. With respect to your answers in question 2, how well does the electoral college system reflect the principle of one person one vote?

Quiz Chapter 17.8

Assumptions and model diagnostics for Simple Linear Regression


Chapter 17 contents

20.5 – Time series

Introduction

Time series refers to any measure recorded over time. Stationary time series do not have trends or seasonality, just random (white) noise; differencing, or nonstationary time series do have trends and or seasonality. Stationary time series will not have predictable patterns over the long term, but for us, what this distinction says is that statistics like autocorrelation, the mean and standard deviation remains the same over time. Nonstationary times series can be made stationary by transformation, with taking a differencing approach, subtracting each observation from its preceding one to remove trends and seasonality, one common approach.

All kinds of examples of time series analysis can be made, with stock market price fluctuations (Hamilton 1994) and meteorological forecasting (Mudelsee 2014) as common examples. Time series analysis are also important in clinical situations, for example, analysis of temporal patterns in ECG and blood pressure data, which helps predict risks, monitor patient health, and understand disease trends. In ecology, perhaps the most famous time series data set is the Hudson’s Bay Company fur-trade records, which show a 9- to 11-year predator-prey population cycle between populations of the Canadian lynx (the predator) and the snowshoe hare (the prey) (Krebs et al 1995).

Significant autocorrelation — the correlation between any two observations in a data series separated by a specific time interval or lag — represents the extent to which a time series is correlated with its past values. For example, autocorrelation could measure the association between a person’s heart rate today and its heart rate yesterday, or between its heart rate today and the heart rate from last week. It is not simply the relationship between today’s heart rate and, for instance, today’s environmental temperature. This kind of comparison, between two sets of time series, calls for a cross-correlation or predictive correlation. A cross-correlation measures the correlation between the first series (temperature) and a lagged version of the second series (heart rate some minutes or hours later). Examples of such correlations include our familiar product moment correlation, but generalized across all possible time lags.

Note 1: See RHRV package,  the R Heart Rate Variability (HRV) analysis package, for framework to analyze heartbeat, ECG, and other cardiac recordings. See also Chapter 20.3 – Baseline correction for an example of a myogram analysis with baseline drift.

There’s much to the analysis of time series, but one key concept is the moving average. Along with any trend or pattern due to seasonality, time series data are expected to exhibit noise or random variation associated with each point in the series. The moving average is an attempt to smooth out data to reveal underlying trends and are fundamental to seasonal decomposition and forecasting. We calculate a series of averages of different subsets of the data, making it easier to spot long-term patterns by filtering out short-term noise, like fluctuations or outliers.

For example, to calculate the 5-beat moving average of a heartbeat, you would average the last 5 individual heartbeat values. As each new heartbeat is recorded, the oldest one is dropped, and a new average is calculated, creating a smoother trend line that shows a clearer overall picture rather than focusing on individual, potentially spiky, beat-to-beat variations. Rate-responsive or adaptive pacemakers use moving averages to determine the appropriate pacing rate. This helps provide a smoother and more stable heart rate response to the patient’s activity.

Note 2: For some really cool work on adaptive pacemakers, see Kumar et al 2018.

This statistical approach should sound familiar — we introduced without much fanfare use of LOESS (Locally Estimated Scatterplot Smoothing) to smooth data to improve pattern detection in Chapter 4.5 and Chapter 17.4. While a moving average takes average of a fixed number of recent data points, LOESS is a more powerful non-parametric regression technique that fits local polynomial regressions to subsets of the data to create a smooth curve.

In time series analysis, the autocorrelation function (ACF) measures the linear relationship between a time series and a lagged version of itself. It quantifies how correlated a series is with its past values (y{t}) and y_{t-k}), where k is the lag or time interval. An ACF plot, or correlogram, visually displays these correlation coefficients at different lags to help identify patterns, assess randomness, and determine appropriate time series models like ARIMA. ACF is related to moving averages because the ACF plot helps to identify the order of a moving average model, which depends on the ACF’s behavior at different lags.

Note 3: A time-series plot shows how a single variable changes over time, while an ACF (Autocorrelation Function) plot visualizes the correlation between a time series and a lagged version of itself.

Like many pages in Mike’s Biostatistics Book, this page only begins to introduce the subject. For a more thorough introduction, see Introduction to Time Series Analysis, NIST. See also the text by Shumway and Stoffer (2025).

ARIMA and ARMA models

ARIMA and ARMA models are fundamental tools for analyzing time series data in biostatistics, especially when the goal is to understand temporal patterns or forecast future values. An ARMA model combines two ideas: autoregression (AR), where the current value depends on previous values, and moving average (MA), where the current value depends on previous error terms. An ARIMA model extends this by adding differencing—the “I” for Integrated—which helps remove trends and make the series stationary. These models are widely used in public health, epidemiology, and biological monitoring because many variables (e.g., infection rates, physiological signals) show correlation over time.

Note 4: We introduced ARMA models in our Generalized Linear models introduction, Chapter 18.4.

Both ARMA and ARIMA models rely on the concepts of lagged dependence and error smoothing, but ARIMA is more flexible because it explicitly accommodates nonstationary data. An ARMA(p, q) model is appropriate when the time series is already stationary or has been preprocessed to remove trend and seasonality. p is the autoregressive order, the number of lagged observations used to forecast the current value, and q is the moving average order, the number of lagged forecast errors included in the model.

In contrast, ARIMA(p, d, q) includes a differencing parameter 𝑑 that automatically transforms the series to stationarity before fitting the ARMA structure. Thus, ARIMA models are typically used for data with a clear trend or evolving mean, while ARMA models are a subset applied to stable series without differencing. In practice, ARIMA is more commonly applied because real-world biological and clinical time series often exhibit trends.

R code

In R, ARMA and ARIMA models can be fit using the forecast or stats packages. The code below shows simple examples of each using a generic time series object y. An ARMA(2,1) model can be fit with:

arma_model <- arima(y, order = c(2, 0, 1))
summary(arma_model)

where the middle “0” indicates no differencing. For an ARIMA(1,1,1) model, which includes first differencing to remove trend, the code is:

arima_model <- arima(y, order = c(1, 1, 1))
summary(arima_model)

ccc

R packages

To conduct time series analysis we can use built in functions like ts() and decompose(). HoltWinters() also useful, now part of stats. Lots of specialized time series packages with advanced features, including forecast, timeSeries (Financial time series), season (Seasonal analysis of health data), and many others. For a more extensive package, see asta, which was designed to accompany the excellent book, now in its 5th edition, Time Series Analysis and its Applications: With R Examples, by Shumway and Stoffer (2025).

Note 4: Caution — newer versions of R have HoltWinters() and related functions included with base package stats.

Rcmdr package for time series was RcmdrPlugin.epack , removed from CRAN as of 2018.

For up-to-date listing of time series packages, see https://cran.r-project.org/web/views/TimeSeries.html

Time series data sets included in R and Rcmdr

R Code

data(co2, package="datasets")
co2 <- as.data.frame(co2)
#convert to time series data type with ts()
tCO2 <- ts(co2,frequency=12,start=c(1959),end=c(1997))
plot.ts(tCO2)

ppm CO2 from Mauna Loa, years 1958-1997, co2 data set in R, datasets package

Figure 1. Time series plot of CO2 data set, the Keeling curve, from package datasets, comes with Rcmdr installation.

Other datasets included with R

carData::Arrests

carData::Bfox

carData::CanPop

Example

Get up-to-date CO2 data from NOAA as text file. Download to your computer, load and clean in your favorite spreadsheet app. Months came as numbers 1,2,3, etc., I changed to text, Jan, Feb, Mar, etc. I grabbed three columns: year, month, ppm for import to R.

head(maunaLoa)

R output

> head(maunaLoa)
  year month  ppm
1 1958 Mar 315.70
2 1958 Apr 317.45
3 1958 May 317.51
4 1958 Jun 317.24
5 1958 Jul 315.86
6 1958 Aug 314.93

However, it turns out the time series functions are easiest to work if only the ppm data are included.

tCO2 <- ts(maunaLoa[,"ppm"],frequency=12,start=c(1958,3),end=c(2020,10))
head(tCO2)

R output

> head(tCO2)
        Mar    Apr    May    Jun    Jul    Aug
1958 315.70 317.45 317.51 317.24 315.86 314.93

Get our plot (Figure 2).

plot(tCO2)

CO2 in ppm from 1958 to November 2020. Data from NOAAA

Figure 2. CO2 ppm monthly average data from NOAA, last data October 2020.

Seasonal time series comes with a trend component, a seasonal component, and a random component.

R code

dectCO2 <- decompose(tCO2)
head(dectCO2)
plot(dectCO2)

decompose CO2

Figure 3. Observed (panel, top), trends over time (panel, second from top), seasonal changes (panel, second from bottom), and random error (panel, bottom).

Forecasting

Excellent resource at https://otexts.com/fpp2/

Exponential smoothing, weighted averages of past observations, weighted so that more recent observations are more influential.

Holt-Winters method extracts seasonal component (additive or multiplicative).

#set start value to value of first observation
tCO2cast <- HoltWinters(tCO2, l.start=315.42)
#Predict for next ten years. Because frequency in ts() was monthly, ten years is h=120
forecastCO2 <- forecast(tCO2cast, h=120)
plot(forecastCO2, fcol="red")

forecast plot

Figure 4. Data in black, predicted values in red (additive) shaded by confidence interval.

Questions

  1. Write up three learning outcomes for this page. Hint: Point your favorite generative AI to this page and ask for help.
  2. For the co2 dataset included in Rcmdr (co2, datasets), obtain forecast for year 2020 and compare against actual 2020 data (see Figure 2).
  3. Positive clinical samples between September 2015 and November 2020 for flu virus in the USA are provided in the data set below (scroll or click here). The frequency of observations was weekly. Apply decompose() and obtain the seasonal and trend components of the data set. Which month does the peak positive sample occur?
  4. Total pounds of fish (variable = Pounds) and pounds of Akule and Opelu (variable = Akule.Opelu) caught by commercial industry in Hawaiʻi, from 2000 to 2018 are provided in the data set below (scroll or click here). Apply decompose() and obtain the seasonal and trend components of the data set for Total pounds and again for Akule (Selar crumenophthalmus) and Opelu (Decapterus macarellus). Is there evidence for  trends, and if so, describe the trend. Is there evidence of seasonality? If so, which month did peak fishing occur?

Quiz Chapter 20.5

Time series

References and suggested reading

Hamilton, J. D. (1994). Time Series Analysis. Princeton University Press.

Krebs, C. J., Boutin, S., Boonstra, R., Sinclair, A. R. E., Smith, J. N. M., Dale, M. R. T., Martin, K., & Turkington, R. (1995). Impact of food and predation on the snowshoe hare cycle. Science, 269(25 August), 1112–1115.

Kumar, A., Komaragiri, R., & Kumar, M. (2018). From Pacemaker to Wearable: Techniques for ECG Detection Systems. Journal of Medical Systems, 42(2), 34.

Chapter 6.4. Introduction to Time Series Analysis, in NIST/SEMATECH e-Handbook of Statistical Methods, https://www.itl.nist.gov/div898/handbook/index.htm, (first reviewed by Mike in 2019).

Mudelsee, M. (2016). Climate time series Classical statistics and bootstrap methods (2nd ed., Vol. 51). Springer.

Shumway, R. H., & Stoffer, D. S. (2025). Time Series Analysis and Its Applications: With R Examples (5th ed.). Springer.

Data set this page

Flu, extracted 28 Nov 2020 from https://gis.cdc.gov/grasp/fluview/fluportaldashboard.html

YearDateWeekPositive
201509/28/15401.056
201510/05/15411.297
201510/12/15421.109
201510/19/15431.108
201510/26/15441.123
201511/02/15451.382
201511/09/15461.193
201511/16/15471.385
201511/23/15481.395
201511/30/15491.475
201512/07/15502.512
201512/14/15512.287
201512/21/15522.46
201601/04/1612.931
201601/11/1624.254
201601/18/1635.485
201601/25/1646.96
201602/01/1659.699
201602/08/16612.549
201602/15/16715.536
201602/22/16818.362
201602/29/16921.11
201603/07/161023.645
201603/14/161119.972
201603/21/161218.471
201603/28/161316.227
201604/04/161414.016
201604/11/161513.236
201604/18/161612.346
201604/25/161710.262
201605/02/16188.121
201605/09/16196.686
201605/16/16205.811
201605/23/16214.719
201605/30/16223.06
201606/06/16233.02
201606/13/16241.829
201606/20/16251.712
201606/27/16261.223
201607/04/16270.903
201607/11/16280.869
201607/18/16290.849
201607/25/16300.782
201608/01/16310.934
201608/08/16320.901
201608/15/16330.803
201608/22/16341.405
201608/29/16351.678
201609/05/16361.461
201609/12/16371.513
201609/19/16381.741
201609/26/16391.784
201610/03/16401.57
201610/10/16411.359
201610/17/16421.403
201610/24/16431.509
201610/31/16441.916
201611/07/16452.201
201611/14/16462.576
201611/21/16473.348
201611/28/16483.319
201612/05/16494.26
201612/12/16506.683
201612/19/165110.782
201612/26/165213.999
201701/02/17113.344
201701/09/17215.373
201701/16/17318.287
201701/23/17418.53
201701/30/17521.422
201702/06/17624.153
201702/13/17724.512
201702/20/17824.725
201702/27/17919.772
201703/06/171019.271
201703/13/171119.034
201703/20/171219.711
201703/27/171318.482
201704/03/171415.425
201704/10/171512.74
201704/17/17169.696
201704/24/17176.768
201705/01/17185.918
201705/08/17195.333
201705/15/17204.863
201705/22/17214.352
201705/29/17224.165
201706/05/17233.386
201706/12/17243.062
201706/19/17252.649
201706/26/17262.534
201707/03/17272.178
201707/10/17282.164
201707/17/17291.839
201707/24/17301.806
201707/31/17311.948
201708/07/17321.9
201708/14/17331.343
201708/21/17341.434
201708/28/17351.935
201709/04/17361.888
201709/11/17371.896
201709/18/17381.669
201709/25/17391.703
201710/02/17402.202
201710/09/17412.09
201710/16/17422.176
201710/23/17432.583
201710/30/17443.607
201711/06/17454.245
201711/13/17465.3
201711/20/17477.088
201711/27/17487.305
201712/04/174910.745
201712/11/175015.355
201712/18/175122.777
201712/25/175225.386
201801/01/18125.365
201801/08/18226.942
201801/15/18327.034
201801/22/18427.37
201801/29/18527.064
201802/05/18626.998
201802/12/18726.117
201802/19/18822.616
201802/26/18918.487
201803/05/181015.694
201803/12/181115.581
201803/19/181215.328
201803/26/181315.114
201804/02/181412.689
201804/09/181511.249
201804/16/18169.398
201804/23/18177.999
201804/30/18186.259
201805/07/18194.393
201805/14/18203.166
201805/21/18212.39
201805/28/18221.529
201806/04/18231.577
201806/11/18241.299
201806/18/18251.023
201806/25/18261.114
201807/02/18271.003
201807/09/18280.916
201807/16/18291.053
201807/23/18300.995
201807/30/18310.954
201808/06/18320.957
201808/13/18330.764
201808/20/18341.336
201808/27/18351.504
201809/03/18361.747
201809/10/18371.687
201809/17/18381.699
201809/24/18391.497
201810/01/18401.749
201810/08/18411.697
201810/15/18421.993
201810/22/18432.055
201810/29/18442.174
201811/05/18452.733
201811/12/18463.157
201811/19/18473.928
201811/26/18483.915
201812/03/18496.232
201812/10/185010.364
201812/17/185114.265
201812/24/185216.352
201912/31/18112.139
201901/07/19212.722
201901/14/19316.317
201901/21/19419.392
201901/28/19522.549
201902/04/19625.134
201902/11/19726.026
201902/18/19826.241
201902/25/19926.074
201903/04/191025.607
201903/11/191126.132
201903/18/191222.481
201903/25/191319.304
201904/01/191414.942
201904/08/191511.909
201904/15/19168.611
201904/22/19175.844
201904/29/19184.82
201905/06/19193.84
201905/13/19203.542
201905/20/19213.42
201905/27/19223.083
201906/03/19232.79
201906/10/19242.316
201906/17/19251.902
201906/24/19262.081
201907/01/19272.429
201907/08/19282.017
201907/15/19292.218
201907/22/19302.377
201907/29/19312.398
201908/05/19322.054
201908/12/19332.082
201908/19/19342.362
201908/26/19353.455
201909/02/19363.097
201909/09/19372.484
201909/16/19382.757
201909/23/19392.744
201909/30/19401.31
201910/07/19411.479
201910/14/19421.552
201910/21/19432.253
201910/28/19443.057
201911/04/19455.163
201911/11/19466.756
201911/18/19479.546
201911/25/194810.939
201912/02/194911.655
201912/09/195016.154
201912/16/195122.533
201912/23/195226.934
202012/30/19123.488
202001/06/20223.119
202001/13/20326.083
202001/20/20428.281
202001/27/20530.147
202002/03/20630.26
202002/10/20729.675
202002/17/20828.322
202002/24/20925.752
202003/02/201022.491
202003/09/201115.813
202003/16/20127.502
202003/23/20132.322
202003/30/20141.031
202004/06/20150.618
202004/13/20160.623
202004/20/20170.218
202004/27/20180.263
202005/04/20190.326
202005/11/20200.306
202005/18/20210.213
202005/25/20220.165
202006/01/20230.34
202006/08/20240.28
202006/15/20250.381
202006/22/20260.282
202006/29/20270.21
202007/06/20280.176
202007/13/20290.376
202007/20/20300.15
202007/27/20310.133
202008/03/20320.176
202008/10/20330.132
202008/17/20340.227
202008/24/20350.315
202008/31/20360.202
202009/07/20370.186
202009/14/20380.4
202009/21/20390.225
202009/28/20400.33
202010/05/20410.401
202010/12/20420.35
202010/19/20430.251
202010/26/20440.201
202011/02/20450.177
202011/09/20460.222

Data set in this page

Fish, Hawaiʻi state DLNR, Pounds refers to total catch, Akule.Opelu refers to pounds for the two kinds of fish.

YearMonthPoundsAkule.Opelu
1999Jan206402385331
1999Feb228678589537
1999Mar2083789112897
1999Apr2446840136301
1999May2300842103692
1999Jun2340116134432
1999Jul2646429138814
1999Aug225440896569
1999Sep192638156598
1999Oct223378976834
1999Nov1730672134706
1999Dec176237592255
2000Jan1501164147104
2000Feb1993373104165
2000Mar2220831132028
2000Apr2398180119224
2000May2557229121268
2000Jun2510298145200
2000Jul227095493883
2000Aug191265469107
2000Sep136526465007
2000Oct161511751208
2000Nov1388453117493
2000Dec1802926121486
2001Jan1481810170702
2001Feb149635644575
2001Mar1579528101764
2001Apr118459189388
2001May2091424124193
2001Jun196688661122
2001Jul211393173266
2001Aug192666129386
2001Sep135342930268
2001Oct133828929577
2001Nov174719880350
2001Dec145833622817
2002Jan1517609107406
2002Feb172908431030
2002Mar174798567691
2002Apr2109451101043
2002May206992157251
2002Jun1640151100501
2002Jul197938287584
2002Aug183167865566
2002Sep173420153162
2002Oct177920793867
2002Nov2191825106167
2002Dec257619167881
2003Jan191050049420
2003Feb207516855006
2003Mar224575371616
2003Apr1562751102993
2003May2440228106600
2003Jun1842907101715
2003Jul195727948453
2003Aug214382369130
2003Sep150321274525
2003Oct161177970949
2003Nov166816754004
2003Dec231253743054
2004Jan160559575751
2004Feb170553394864
2004Mar2079402120305
2004Apr188370490950
2004May1830168111599
2004Jun191862276392
2004Jul202978798937
2004Aug192800972577
2004Sep162022482650
2004Oct185464374587
2004Nov198156759753
2004Dec202227244353
2005Jan208882160972
2005Feb210694859469
2005Mar238632784551
2005Apr2122171101099
2005May236995379042
2005Jun2342117104814
2005Jul228187171065
2005Aug212430353383
2005Sep173498637195
2005Oct192013148632
2005Nov196950688235
2005Dec232393398768
2006Jan170276650553
2006Feb206020489037
2006Mar224457033916
2006Apr206892274430
2006May2164076108689
2006Jun193595189503
2006Jul196851393758
2006Aug1741802111080
2006Sep150889744537
2006Oct189253546747
2006Nov220817382938
2006Dec138141242260
2007Jan2211384114496
2007Feb239143760618
2007Mar272402194251
2007Apr263924590078
2007May3168913129258
2007Jun2706972116628
2007Jul2523392129345
2007Aug227250288997
2007Sep212183771560
2007Oct247299652915
2007Nov3040118107555
2007Dec293417439239
2008Jan265653944672
2008Feb310181935213
2008Mar281684674421
2008Apr306483763355
2008May356099352287
2008Jun292021933685
2008Jul251656131288
2008Aug233820562171
2008Sep231445831311
2008Oct240724042766
2008Nov206066675102
2008Dec232926874508
2009Jan219856944459
2009Feb231476433206
2009Mar184645964879
2009Apr265923036638
2009May269244077011
2009Jun238717549217
2009Jul267289555033
2009Aug217402740398
2009Sep225915351386
2009Oct238674958095
2009Nov208170651798
2009Dec270287155148
2010Jan205996440855
2010Feb2632985100598
2010Mar243056239887
2010Apr265201340528
2010May246022871483
2010Jun2743053120553
2010Jul227884796315
2010Aug261842762854
2010Sep248386166613
2010Oct250332153353
2010Nov2370032104360
2010Dec243104757919
2011Jan252724137755
2011Feb278645351863
2011Mar378907640188
2011Apr314882660494
2011May301518749037
2011Jun271858358380
2011Jul228452143096
2011Aug247551933612
2011Sep246164048697
2011Oct242055449929
2011Nov205976963045
2011Dec288277664430
2012Jan282511642894
2012Feb265389223528
2012Mar254475839839
2012Apr305010947250
2012May326466641357
2012Jun279820456808
2012Jul333117446853
2012Aug286408862682
2012Sep221953633641
2012Oct248216247478
2012Nov254514249232
2012Dec312950735924
2013Jan290274832373
2013Feb238819721922
2013Mar283127941718
2013Apr246744454619
2013May313115357183
2013Jun281998333484
2013Jul347318044240
2013Aug258686352288
2013Sep245925838145
2013Oct322831748533
2013Nov299873253187
2013Dec302391833381
2014Jan250373331233
2014Feb261518433134
2014Mar280863938876
2014Apr285751445819
2014May336374658283
2014Jun277868954266
2014Jul282884741221
2014Aug307406139744
2014Sep270344040668
2014Oct274481337263
2014Nov254114372020
2014Dec332579944128
2015Jan313082254942
2015Feb280602045098
2015Mar356086653378
2015Apr334169543642
2015May371748770583
2015Jun367828356578
2015Jul395446053615
2015Aug301610042015
2015Sep220972438904
2015Oct279540955583
2015Nov342675370399
2015Dec335745451095
2016Jan308723154089
2016Feb337448548683
2016Mar326005445472
2016Apr293010663926
2016May338333176757
2016Jun320961345557
2016Jul276514337198
2016Aug273286740213
2016Sep218034741660
2016Oct229834834699
2016Nov254557471924
2016Dec369148537448
2017Jan338329748974
2017Feb285658435716
2017Mar341303939789
2017Apr336115630625
2017May357641031092
2017Jun334846927734
2017Jul274118727041
2017Aug267562532476
2017Sep270067533394
2017Oct277915931373
2017Nov281701240681
2017Dec372621633955
2018Jan336159146166
2018Feb262526329890
2018Mar321910231454
2018Apr359328725954
2018May379828535908
2018Jun336282931899
2018Jul273532630968
2018Aug239754919849
2018Sep232373529324
2018Oct247245128927
2018Nov268746640497
2018Dec323629336603

/MD


Chapter 20 contents

/MD