Learn R Programming

itsadug (version 2.4.1)

resid_gam: Extract model residuals and remove the autocorrelation accounted for.

Description

Extract model residuals and remove the autocorrelation accounted for.

Usage

resid_gam(model, AR_start = NULL, incl_na = FALSE, return_all = FALSE)

Arguments

model

A GAMM model build with gam or bam.

AR_start

Optional: vector with logicals, indicating the start of events. Default is NULL, because generally the function can retrieve all necessary information from the model.

incl_na

Whether or not to include missing values (NA)when returning the residuals. Defaults to FALSE.

return_all

Default is FALSE. Returns a list with normal residuals, corrected residuals, and the value of rho.

Value

Corrected residuals.

See Also

resid, missing_est

Other functions for model criticism: acf_n_plots(), acf_plot(), acf_resid(), derive_timeseries(), start_event(), start_value_rho()

Examples

Run this code
# NOT RUN {
data(simdat)

# }
# NOT RUN {
# Add start event column:
simdat <- start_event(simdat, event=c('Subject', 'Trial'))
head(simdat)
# bam model with AR1 model (toy example, not serious model):
m1 <- bam(Y ~ Group + te(Time, Trial, by=Group), 
   data=simdat, rho=.5, AR.start=simdat$start.event)
# Standard residuals:
res1 <- resid(m1)
# Corrected residuals:
res2 <- resid_gam(m1)

# Result in different ACF's:
par(mfrow=c(1,2))
acf(res1)
acf(res2)

# Without AR.start included in the model:
m2 <- bam(Y ~ Group + te(Time, Trial, by=Group), 
   data=simdat)
acf(resid_gam(m2), plot=F)
# Same as resid(m2)!
acf(resid(m2), plot=F)

### MISSING VALUES ###
# Note that corrected residuals cannot be calculated for the last 
# point of each time series. These missing values are by default
# excluded.

# Therefore, this will result in an error...
simdat$res <- resid_gam(m1)
# ... and this will give an error too:
simdat$res <- NA
simdat[!is.na(simdat$Y),] <- resid_gam(m1)
# ... but this works:
simdat$res <- resid_gam(m1, incl_na=TRUE)

# The parameter incl_na will NOT add missing values
# for missing values in the *data*. 
# Example:
simdat[sample(nrow(simdat), 15),]$Y <- NA
# Without AR.start included in the model:
m2 <- bam(Y ~ Group + te(Time, Trial, by=Group), 
   data=simdat)
# This works:
acf(resid_gam(m2))
# ...but this results in error, although no AR1 model specified:
simdat$res <- resid_gam(m2)
# ... for this type of missing data, this does not solve the problem:
simdat$res <- resid_gam(m2, incl_na=TRUE)
# instead try this:
simdat$res <- NA
simdat[-missing_est(m2),]$res <- resid_gam(m2)

# With AR.start included in the model:
m1 <- bam(Y ~ Group + te(Time, Trial, by=Group), 
   data=simdat, rho=.5, AR.start=simdat$start.event)
# This works (incl_na=TRUE):
simdat$res <- NA
simdat[-missing_est(m2),]$res <- resid_gam(m2, incl_na=TRUE)

# }

Run the code above in your browser using DataLab