| Title: | Lagged Procrustean Randomization Test for Multivariate Time Series |
|---|---|
| Description: | Extends the Procrustean randomization test (PROTEST; Jackson (1995) <doi:10.1080/11956860.1995.11682297>; Peres-Neto and Jackson (2001) <doi:10.1007/s004420100720>) to ordered multivariate series. Concordance between two configurations is scanned across candidate temporal lags. Significance is assessed with phase-randomized surrogates (default), cyclic shifts of the full series or free permutation of rows, and a global max-statistic p-value accounts for scanning several lags and selecting the best one. Returns the lag profile, the lag of maximal concordance and per-observation Procrustes residuals. |
| Authors: | Diogo B. Provete [aut, cre] (ORCID: <https://orcid.org/0000-0002-0097-0651>) |
| Maintainer: | Diogo B. Provete <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.9.1.9000 |
| Built: | 2026-11-22 18:54:52 UTC |
| Source: | https://github.com/diogoprov/lagprotest |
Returns the lag profile in long (tidy) form, one row per lag, ready for tables or plotting with other tools.
## S3 method for class 'lagged_protest' as.data.frame(x, row.names = NULL, optional = FALSE, alpha = 0.05, ...)## S3 method for class 'lagged_protest' as.data.frame(x, row.names = NULL, optional = FALSE, alpha = 0.05, ...)
x |
A |
row.names, optional
|
Unused; for compatibility with the generic. |
alpha |
Level of the permutation null quantile in |
... |
Unused. |
A data frame with the columns of x$profile (lag, n, m2,
r, p.value, p.adjusted, nperm, z, a), plus null.quantile, the
alpha quantile of the permuted at each lag (unadjusted),
and optimal, which flags the optimal lag.
plot.lagged_protest(), autoplot.lagged_protest()
sim <- simulate_lagged_series(n_times = 12, true_lag = 2, noise_sd = 0.3, seed = 1) fit <- lagged_protest(sim$X, sim$Y, lags = 0:4, nperm = 199, seed = 1) as.data.frame(fit)sim <- simulate_lagged_series(n_times = 12, true_lag = 2, noise_sd = 0.3, seed = 1) fit <- lagged_protest(sim$X, sim$Y, lags = 0:4, nperm = 199, seed = 1) as.data.frame(fit)
A ggplot2 version of plot.lagged_protest(): against lag, with
the alpha quantile of the permutation null distribution at each lag as
a dashed line, filled points for lags whose p-value (adjusted, if
p.adjust.method was not "none") is below alpha, and the optimal lag
circled, filled when the global p-value is below alpha. The global
p-value is shown in the subtitle. Requires the ggplot2 package.
## S3 method for class 'lagged_protest' autoplot(object, alpha = 0.05, ...)## S3 method for class 'lagged_protest' autoplot(object, alpha = 0.05, ...)
object |
A |
alpha |
Significance level. |
... |
Unused. |
A ggplot object, which can be modified with further layers.
plot.lagged_protest(), as.data.frame.lagged_protest()
sim <- simulate_lagged_series(n_times = 12, true_lag = 2, noise_sd = 0.3, seed = 1) fit <- lagged_protest(sim$X, sim$Y, lags = 0:4, nperm = 199, seed = 1) library(ggplot2) autoplot(fit) autoplot(fit) + theme_bw()sim <- simulate_lagged_series(n_times = 12, true_lag = 2, noise_sd = 0.3, seed = 1) fit <- lagged_protest(sim$X, sim$Y, lags = 0:4, nperm = 199, seed = 1) library(ggplot2) autoplot(fit) autoplot(fit) + theme_bw()
Monthly means of four hepatic modules and of climate for the treefrog Dendropsophus minutus at a site in southeastern Brazil (20.8992° S, 49.3502° W), sampled independently each month from April 2016 to March 2017. Each module is a set of variables measured on the same individuals, averaged by month, so every element is a 12-row series covering one annual cycle.
dminutus_liverdminutus_liver
A named list of five numeric matrices, each with 12 rows (months,
named "2016-04" to "2017-03"):
SomaticScaled mass index (mean_smi), hepatosomatic index
(mean_ihs), body mass (mean_weight) and snout–vent length
(mean_size).
HistochemistryMean area of hemosiderin (hemosiderin),
glycogen (mean_gli), melanin (mean_mel) and lipofuscin
(mean_lipo) per image.
MorphometryHepatocyte area and volume (mean_cellA,
mean_cellV), nuclear volume and area (mean_nuV, mean_nuA) and
nucleus–cytoplasm ratio (mean_ncr).
DensityVolumetric density of hepatocytes, sinusoids,
melanomacrophage centers (cmm) and portal tissue, as centered
log-ratios.
ClimateMean daily minimum and maximum temperature (Tmin,
Tmax, °C), Palmer drought severity index (Drought), mean daily
rainfall (Rainfall, mm), relative humidity (RH, %), UV-B
irradiance (UVB, J m per day) and photoperiod with
civil twilight (photoperiod, h).
Hepatic data: Franco-Belussi, L., Moraes, L., de Oliveira, C., Fernandes, C. E. and Provete, D. B. (2026). Data and code for: Seasonal hepatic plasticity follows a temporal response hierarchy in a Neotropical frog. Zenodo. doi:10.5281/zenodo.21613832. Licensed under CC BY 4.0.
Climate: temperature, rainfall and humidity from BR-DWGD (Xavier et al. 2022, doi:10.1002/joc.7731); drought from TerraClimate (Abatzoglou et al. 2018, doi:10.1038/sdata.2017.191); UV-B from glUV (Beckmann et al. 2014, doi:10.1111/2041-210X.12168); photoperiod computed for the site coordinates. Cite these sources when using the corresponding variables.
str(dminutus_liver) fit <- lagged_protest(dminutus_liver$Climate, dminutus_liver$Histochemistry, lags = 0:3, nperm = 199, seed = 1) fit$optimal_lagstr(dminutus_liver) fit <- lagged_protest(dminutus_liver$Climate, dminutus_liver$Histochemistry, lags = 0:3, nperm = 199, seed = 1) fit$optimal_lag
Builds two monthly blocks, environment and fish, for one habitat of the
Patos Lagoon estuary, southern Brazil, from the PELD-ELPA beach-seine
survey (Darwin Core Archive v1.16). The data are licensed CC BY-NC 4.0
and are not shipped with lagprotest: pass a local copy of the
archive in path, or leave path = NULL to download it from the SiBBr
IPT into the session's temporary directory.
elpa_blocks( habitat = c("estuary", "sandy beach"), from = c(1996, 8), to = c(2016, 12), species = NULL, hellinger = TRUE, path = NULL )elpa_blocks( habitat = c("estuary", "sandy beach"), from = c(1996, 8), to = c(2016, 12), species = NULL, hellinger = TRUE, path = NULL )
habitat |
|
from, to
|
Integer vectors |
species |
Species (scientific names) to keep in the fish block.
|
hellinger |
Logical. If |
path |
Path to the archive ( |
Each sampling event is one site in one month, with five seine hauls. Counts are summed by species within an event and divided by five (catch per haul), and both catch and environment are averaged over the sites of the chosen habitat in each month. Months with no record of an environmental variable are filled by linear interpolation; a month with no fish sampling at all is an error, since the blocks must be regular series. No transformation, detrending or deseasonalization is applied to the environment; see the example for the steps used in the lagprotest preprint, which also added freshwater discharge from the Brazilian National Water Agency (not included here).
A named list of two numeric matrices with one row per month (row
names "YYYY-MM"):
EnvironmentWater temperature (temp, °C), salinity (sal)
and Secchi depth (secchi).
FishOne column per species in species.
Vieira, J. P., Garcia, A. M. and Lemos, V. M. PELD-ELPA: Species composition and abundance patterns of fish assemblages at shallow waters of Patos Lagoon estuary. Version 1.16. Sistema de Informação sobre a Biodiversidade Brasileira (SiBBr), via GBIF, doi:10.15468/kci8zb. Licensed CC BY-NC 4.0: cite the dataset and do not use it commercially. The program is described in Lemos et al. (2022), Earth System Science Data 14: 1015–1041, doi:10.5194/essd-14-1015-2022.
el <- elpa_blocks("estuary") detrend <- function(m) { apply(m, 2, function(x) residuals(lm(x ~ seq_along(x)))) } X <- detrend(log1p(el$Environment)) Y <- detrend(el$Fish) fit <- lagged_protest(X, Y, lags = 0:6, period = 12, nperm = 999, seed = 1) fitel <- elpa_blocks("estuary") detrend <- function(m) { apply(m, 2, function(x) residuals(lm(x ~ seq_along(x)))) } X <- detrend(log1p(el$Environment)) Y <- detrend(el$Fish) fit <- lagged_protest(X, Y, lags = 0:6, period = 12, nperm = 999, seed = 1) fit
Scans Procrustes concordance between two multivariate series across candidate temporal lags and tests it by permutation at each lag.
lagged_protest( X, Y, lags = 0:6, permutation = c("phase", "cyclic", "free"), nperm = 999, mirror = TRUE, bidirectional = FALSE, scale = TRUE, stat = NULL, p.adjust.method = "none", period = NULL, deseason = c("none", "monthly"), prewhiten = c("none", "prais"), seed = NULL )lagged_protest( X, Y, lags = 0:6, permutation = c("phase", "cyclic", "free"), nperm = 999, mirror = TRUE, bidirectional = FALSE, scale = TRUE, stat = NULL, p.adjust.method = "none", period = NULL, deseason = c("none", "monthly"), prewhiten = c("none", "prais"), seed = NULL )
X, Y
|
Numeric matrices or data frames with rows as ordered time
points and columns as variables, or |
lags |
Integer vector of non-negative candidate lags (default
|
permutation |
Permutation scheme, |
nperm |
Number of surrogates ( |
mirror |
Logical; with |
bidirectional |
Logical; if |
scale |
Logical; z-score the columns of |
stat |
Scan statistic used for the global p-value and the optimal
lag: |
p.adjust.method |
Correction of the per-lag p-values for multiple
lags: |
period |
Optional length of the seasonal cycle, in rows (e.g., 12
for monthly data with an annual cycle). No calendar is assumed: months
of different lengths and leap years are ignored, and every row counts
as one time step. Lags are counted in the same rows. If given,
|
deseason |
|
prewhiten |
|
seed |
Optional integer seed for the |
Rows of X and Y are ordered time points (e.g., monthly centroids) and
must correspond one to one. At lag k > 0, X at time t is paired with
Y at time t + k (X leads Y), and the series are truncated to the
overlapping window of n - k rows. Negative lags (Y leads X) are tested
when bidirectional = TRUE. The statistic at each lag is the symmetric
Procrustes sum of squares from vegan::procrustes(). The
optimal lag is chosen by the scan statistic set by stat (by default the
lag with the smallest per-lag p-value, or the smallest under
the cyclic scheme; see below).
Three permutation schemes are available:
"phase" (default): nperm phase-randomized surrogates of Y are
drawn. Each surrogate keeps the amplitude spectrum of every column of
Y (hence its autocorrelation) and the cross-spectra among its columns,
but receives new Fourier phases, shared by all columns. Surrogates are
applied jointly to all lags and do not reproduce the observed alignment,
which makes this the recommended scheme for the global p-value. It
assumes that Y is second-order stationary (constant mean and
variance, and an autocovariance that depends only on the time
separation), so trends should be removed before the test, as in the
example of elpa_blocks(); a message is given when a linear time
trend explains, on average, more than 70% of the variance of the
columns of X or Y (after deseason and prewhiten), a level that
a single seasonal cycle does not reach. It also
treats the series as periodic with period n. In simulations, it was
liberal for short, strongly autocorrelated series (AR(1) of 0.7 or more
with n of 48 or less). It also assumes
that any seasonal cycle shared by X and Y is close to sinusoidal:
new phases destroy the alignment among the harmonics of an abrupt cycle
(a sawtooth or a short pulse), so the surrogates no longer share the
shape of the cycle, and the test can be strongly liberal (Type I error
of 0.10 to 0.34 in simulations with simulate_lagged_series(waveform = "sawtooth") or "pulse", 24 or 48 monthly samples). When the series
span several whole cycles, removing from both the mean of each position
in the cycle (e.g., the mean of each calendar month; deseason = "monthly") restored the Type I error in those simulations.
"cyclic": the full Y series is cyclically shifted by
1, ..., n - 1 positions before lagging, and optionally also
time-reversed (mirror = TRUE). This keeps the temporal autocorrelation
of Y under the null. All n - 1 (or 2(n - 1)) shifts are enumerated,
so nperm and seed are ignored, and the smallest attainable p-value is
1 / (2(n - 1) + 1) (0.043 for n = 12 with mirror = TRUE). The scheme
assumes the series spans complete cycles, i.e., that its period matches
the number of rows (e.g., 12 monthly samples of an annual cycle).
Because a shift of Y combined with lag k is equivalent to another
lag, some shifts reproduce the observed alignment at other lags; the
global p-value (see below) is then valid but has low power, and the
scheme is best used as a conservative check of the phase scheme. Its
default scan statistic is "raw": with "minP", many shifts tie at
the smallest per-lag p-value, and in simulations the global p-value
could not fall below 0.05 with up to 96 rows and lags -6 to 6, so the
test never rejected.
"free": rows of Y are permuted at random, as in
vegan::protest(), and the permuted series is then lagged like the
observed one. This assumes exchangeable rows and can
strongly inflate Type I error when both series are autocorrelated
(Manly and Navarro Alberto 2020, ch. 10).
Both the phase and the cyclic schemes treat the series as periodic with
period n. When the series contains a seasonal cycle whose length does
not divide n (e.g., 18 monthly samples of an annual cycle), no scheme is
calibrated, because two series sharing a period are Procrustes-concordant
whatever their phase. Supplying period truncates both series to their
first floor(n / period) * period rows, so that the analysis spans whole
cycles. In simulations, this restored the Type I error of series that
already spanned complete cycles, whereas removing the seasonal component
by harmonic regression did not.
Two optional preprocessing steps are applied to both series, in this
order, after truncation to whole cycles and before the columns are
standardized (scale):
deseason = "monthly" subtracts from every column the mean of each
position in the cycle (e.g., the mean of each calendar month), so that
the test addresses the anomalies rather than a seasonal cycle that both
series may share. It requires period and at least two whole cycles;
the first row is taken as position 1 of the cycle. In simulations, it
restored the Type I error of the phase scheme for shared seasonal cycles
of any shape (see the caveat on non-sinusoidal cycles above), whereas
removing two harmonics by regression did not suffice for a sawtooth.
The scan then measures concordance among anomalies only. With
strongly autocorrelated noise (AR(1) of 0.9), it remained slightly
liberal (up to about 0.08).
prewhiten = "prais" removes AR(1) autocorrelation from every column by
the Prais-Winsten transformation, for the
first row and for the others, with
the lag-1 autocorrelation of the column (returned in
rho). Unlike ordinary prewhitening, it keeps all n rows: dropping
the first row after removing seasonal means made the test strongly
liberal in simulations, and so did prewhitening before removing them.
For strongly autocorrelated series without seasonality, prewhitening
brought the Type I error of the phase scheme from 0.10–0.19 back to
the nominal level, and it increased power when the anomalies were
strongly autocorrelated. Combined with deseason, it can be liberal
when an abrupt seasonal cycle varies in amplitude among years and the
noise is strongly autocorrelated (about 0.10 in simulations with a
sawtooth cycle and AR(1) of 0.9), where deseason alone was not. A
warning is issued when it is requested for a seasonal series (period
given) without deseason, a combination that inflated the Type I
error in simulations.
With a single cycle (n equal to period), seasonal means cannot be
separated from the signal; a message then recalls that the phase scheme
assumes a close-to-sinusoidal shared cycle.
P-values are computed as (b + 1) / (N + 1), where b is the number of
permuted values smaller than or equal to the observed one and
N the number of permutations (Manly and Navarro Alberto 2020, p. 57).
Each permutation is applied jointly to all lags. The validity of the test
does not depend on N, only the precision of the p-value does; Manly and
Navarro Alberto (2020, pp. 57–59) recommend at least 1000 randomizations
for a test at the 5% level and about 5000 at the 1% level. A message is
issued when the smallest attainable p-value, 1 / (N + 1), is 0.05 or
more.
Because the p-value is bounded by N and conflates strength with sample
size, three continuous measures are computed from the same permutations.
At each lag, standardizes the
observed against its permutation mean and standard deviation,
and expresses the concordance
relative to its null mean. The effect lag is the lag of the largest
(which weighs lags of different overlap more evenly than the raw
), and each permutation selects its own lag in the same way.
Z is the standardized position of the observed maximum within
the permuted maxima; A and the corrected RV coefficient are
chance-corrected at the effect lag as
, with the null mean taken
over the permutations at their own selected lags. A and the corrected RV
are near 0 under the null and 1 for perfect concordance; Z is near 0
under the null. Each permuted is computed in the same way as the
observed one, against the mean and standard deviation of the other values
at that lag (the remaining permutations and the observed), so that the
observed and the permuted values are treated alike.
The mean lag-1 autocorrelation of the columns of each series is returned
in ar1, both raw and after removing by regression the harmonics of
period n (and of period, when given). It is descriptive only: the
raw value is dominated by any seasonal cycle, and the residual value is
biased downwards in short series. The phase scheme was liberal for short,
strongly autocorrelated series in simulations, so both values help judge
whether that caveat applies.
The per-lag p-values (p.value) are not corrected for testing several
lags, nor for selecting the lag with the smallest . Reporting the
raw p-value at the optimal lag therefore inflates Type I error roughly to
the rate at which any lag is significant. The global p-value (p.global)
accounts for both: it compares the most extreme observed score across
lags with the distribution of the most extreme score across lags under
each permutation (a max-statistic test), so it is the p-value of the whole
scan-and-select procedure and is the one to report for the optimal lag.
Because at neighboring lags is strongly correlated, a Bonferroni
level of for lags would be conservative: the
appropriate level lies between and , and
taking the extreme statistic across tests in each randomization, as here,
finds it from the data (Manly and Navarro Alberto 2020, pp. 83–84). The
same source recommends at least randomizations for
tests.
With p.adjust.method = "maxT", every lag receives the corresponding
single-step adjusted p-value for the chosen stat, and the adjusted
p-value at the optimal lag equals p.global. Any method of
stats::p.adjust() can be requested instead; with few permutations, as
in the cyclic scheme, corrections such as Holm may make significance
unattainable: in simulations of the cyclic scheme with up to 96 rows,
Holm-corrected per-lag p-values never fell below 0.05.
The score compared across lags is set by stat:
"minP" (default for the phase and free schemes): the per-lag
p-value. The global statistic is the smallest p-value across lags,
and its null distribution is obtained by
converting every permuted to a p-value within its own lag,
as its rank among the observed and permuted values divided by
, exactly as the observed p-value is computed (the minP
procedure of Westfall and Young 1993; Ge et al. 2003). The
optimal lag is the one with the smallest p-value; ties, common with few
permutations, are broken by and then by .
"z": centered and scaled by the mean and standard deviation
of its own null distribution, with each permuted value standardized
against the others and the observed (see above). The optimal lag is the
one with the largest and equals the effect lag.
"raw" (default for the cyclic scheme): itself, the
statistic of versions up to 0.6. The optimal lag is the one with the
smallest .
All three are computed from the same permutations and give valid global
tests. They differ in how power is spread across lags, because
values at different lags are based on different numbers of
rows (n - |k|), and is smaller and more variable when fewer
rows overlap. Under "raw", the optimal lag therefore tends to fall at
the longest lags scanned, even when the series are independent: in 200
pairs of independent series simulated with simulate_lagged_series()
(n_times = 12, lags -3 to 3), it fell at in about half of
the replicates rather than in two of seven, and the test had less power
for a true lag of zero. "minP" and "z" place every lag on the scale
of its own null distribution, so the optimal lag is close to uniform
across lags under independence. Because the observed and the permuted
scores are computed in the same way, all three give exact tests when the
permutations are exchangeable with the observed series (free and cyclic
schemes). "minP" is conservative when the permutations are few relative
to the number of lags, because per-lag p-values are discrete, and "z"
then has more power. The same reasoning motivates selecting among
candidates by p-value in conditional inference trees (Hothorn et al.
2006). Because per-lag p-values are discrete, the smallest global p-value
that "minP" can reach grows with the number of lags: roughly
for lags and permutations, so
should be at least (Manly and Navarro Alberto 2020,
p. 84), and a message is issued when p < 0.05 cannot be reached. With the
cyclic scheme, permutations are few, and "z" is then preferable.
When the optimal lag and the effect lag differ, print() says so;
candidate lags should be kept within a range justified by the biology of
the system.
An object of class "lagged_protest", a list with:
optimal_lagLag selected by stat (see Details).
m2 at the optimal lag.
rProcrustes correlation, , at the
optimal lag.
p.valueRaw permutation p-value at the optimal lag.
p.adjustedP-value at the optimal lag adjusted with
p.adjust.method (equal to p.value when "none").
p.globalP-value of the scan across lags for stat,
accounting for testing several lags and selecting the optimal one.
npermNumber of permutations or surrogates, the same at every lag (the exact count for the cyclic scheme).
profileData frame with lag, n (rows used), m2, r,
p.value, p.adjusted, nperm, z and a for every lag.
residualsData frame of per-observation Procrustes residuals
at the optimal lag, with the paired row labels of X and Y.
procrustesThe vegan::procrustes() fit at the optimal lag.
effectList with the effect lag (largest ), Z,
A and the chance-corrected RV coefficient at that lag (see
Details).
ar1Data frame with the mean lag-1 autocorrelation of the
columns of X and Y, as analyzed (after any preprocessing), raw
and residual after removing the harmonics of period n and
period.
nullList of permuted values, one element per lag;
element i of every vector comes from the same permutation.
null.rvList of permuted RV coefficients, paired with
null.
rhoWith prewhiten = "prais", a list with the AR(1)
coefficients used for the columns of X and Y; otherwise NULL.
permutation, stat, mirror, p.adjust.method, n, period,
deseason, prewhiten, call
Settings used; mirror is NA
unless the scheme is cyclic, and n is the number of rows after any
truncation to whole cycles.
:protest():
vegan::protest() tests concordance at a single alignment of rows with
free permutation. At lags = 0 with permutation = "free" and
scale = FALSE, lagged_protest() returns the same and
correlation. It extends that implementation for ordered series with the
scan across lags, null distributions that preserve autocorrelation, and
the global p-value for the scan.
Character arguments (permutation, stat, p.adjust.method,
deseason, prewhiten) are case-sensitive and may be abbreviated, as in
match.arg().
Ge, Y., Dudoit, S. and Speed, T. P. (2003). Resampling-based multiple testing for microarray data analysis. Test 12, 1–77. doi:10.1007/BF02595811
Hothorn, T., Hornik, K. and Zeileis, A. (2006). Unbiased recursive partitioning: a conditional inference framework. Journal of Computational and Graphical Statistics 15, 651–674. doi:10.1198/106186006X133933
Jackson, D. A. (1995). PROTEST: a PROcrustean Randomization TEST of community environment concordance. Écoscience 2, 297–303. doi:10.1080/11956860.1995.11682297
Manly, B. F. J. and Navarro Alberto, J. A. (2020). Randomization, Bootstrap and Monte Carlo Methods in Biology, 4th ed. Chapman and Hall/CRC, New York. doi:10.1201/9780429329203
Peres-Neto, P. R. and Jackson, D. A. (2001). How well do multivariate data sets match? The advantages of a Procrustean superimposition approach over the Mantel test. Oecologia 129, 169–178. doi:10.1007/s004420100720
Westfall, P. H. and Young, S. S. (1993). Resampling-Based Multiple Testing: Examples and Methods for p-Value Adjustment. Wiley, New York.
vegan::protest(), vegan::procrustes()
sim <- simulate_lagged_series(n_times = 12, true_lag = 2, noise_sd = 0.3, seed = 1) fit <- lagged_protest(sim$X, sim$Y, lags = 0:4, seed = 1) fit fit$p.global # Conservative check with cyclic shifts (scan statistic "raw") fit_cyclic <- lagged_protest(sim$X, sim$Y, lags = 0:4, permutation = "cyclic") fit_cyclic$profile plot(fit) residuals(fit) # Four years of monthly data sharing an abrupt seasonal cycle: test the # anomalies, with AR(1) prewhitening saw <- simulate_lagged_series(n_times = 48, true_lag = 2, waveform = "sawtooth", noise_sd = 1, seed = 1) lagged_protest(saw$X, saw$Y, lags = 0:4, period = 12, deseason = "monthly", prewhiten = "prais", seed = 1)sim <- simulate_lagged_series(n_times = 12, true_lag = 2, noise_sd = 0.3, seed = 1) fit <- lagged_protest(sim$X, sim$Y, lags = 0:4, seed = 1) fit fit$p.global # Conservative check with cyclic shifts (scan statistic "raw") fit_cyclic <- lagged_protest(sim$X, sim$Y, lags = 0:4, permutation = "cyclic") fit_cyclic$profile plot(fit) residuals(fit) # Four years of monthly data sharing an abrupt seasonal cycle: test the # anomalies, with AR(1) prewhitening saw <- simulate_lagged_series(n_times = 48, true_lag = 2, waveform = "sawtooth", noise_sd = 1, seed = 1) lagged_protest(saw$X, saw$Y, lags = 0:4, period = 12, deseason = "monthly", prewhiten = "prais", seed = 1)
Runs lagged_protest() on pairs of data sets from a named list, such as
the modules of a multi-trait study measured on the same time points, and
collects the results in one table.
lagged_protest_pairs( data, pairs = NULL, lags = 0:6, bidirectional = TRUE, p.adjust.method = "BH", seed = NULL, ... )lagged_protest_pairs( data, pairs = NULL, lags = 0:6, bidirectional = TRUE, p.adjust.method = "BH", seed = NULL, ... )
data |
A named list of numeric matrices, data frames or |
pairs |
Pairs to analyze: |
lags, bidirectional
|
Passed to |
p.adjust.method |
Correction of the global p-values across pairs,
any method of |
seed |
Passed to |
... |
Further arguments passed to |
By default every unordered pair is analyzed once with
bidirectional = TRUE, so both directions are covered by the sign of the
lag: a positive optimal lag means that the first data set of the pair
(x) leads the second (y), and a negative one that y leads x. The
global p-values of the pairs are then adjusted for the number of pairs
with p.adjust.method, because the max-statistic test accounts for the
lags scanned within a pair but not for the pairs examined.
Every pair uses the same seed, so results do not depend on the order or
number of pairs.
A data frame with one row per pair and columns x, y,
optimal_lag, n (rows at the optimal lag), m2, r, p.value (raw
p at the optimal lag), p.global, effect_lag (the lag of the largest
standardized concordance ), the effect measures Z, A and the
corrected RV at effect_lag (see effect in lagged_protest()), and
p.global.adjusted (adjusted across pairs). effect_lag can differ
from optimal_lag, which favors long lags (see Details in
lagged_protest()). Unlike m2, Z, A and RV are on a common
scale across pairs with different numbers of rows. The
lagged_protest() fits are stored, named "x -> y", in the attribute
"fits".
sim <- simulate_lagged_series(n_times = 12, true_lag = 2, noise_sd = 0.3, seed = 1) blocks <- list(A = sim$X, B = sim$Y, C = simulate_lagged_series(n_times = 12, seed = 2)$X) res <- lagged_protest_pairs(blocks, lags = 0:3, nperm = 199, seed = 1) res plot(attr(res, "fits")[["A -> B"]])sim <- simulate_lagged_series(n_times = 12, true_lag = 2, noise_sd = 0.3, seed = 1) blocks <- list(A = sim$X, B = sim$Y, C = simulate_lagged_series(n_times = 12, seed = 2)$X) res <- lagged_protest_pairs(blocks, lags = 0:3, nperm = 199, seed = 1) res plot(attr(res, "fits")[["A -> B"]])
Builds three monthly blocks (environment, phytoplankton and zooplankton)
for Lake Washington, Washington, USA, from lakeWAplanktonRaw in the
MARSS package. The data are not shipped with lagprotest;
this function reads them from an installed copy of MARSS, which
must be installed separately.
lakewa_blocks(from = 1962, to = 1994, interpolate = TRUE)lakewa_blocks(from = 1962, to = 1994, interpolate = TRUE)
from, to
|
First and last year to keep (between 1962 and 1994). |
interpolate |
Logical. Fill missing values by linear interpolation?
If |
Rows are restricted to the years from to to. Missing values (a few
isolated months in each column) are filled by linear interpolation over
the month index when interpolate = TRUE; a gap at either end of the
selected period is filled with the nearest observed value. Plankton
counts are then transformed with log1p(). The environmental variables
are left on their original scale, since lagged_protest() standardizes
columns by default (scale = TRUE).
A named list of three numeric matrices with one row per month
(row names "YYYY-MM"):
EnvironmentWater temperature (Temp, °C), total
phosphorus (TP) and pH.
Phytoplanktonlog1p of the counts (cells per mL) of
Cryptomonas, Diatoms, Greens, Unicells and Other.algae.
Zooplanktonlog1p of the counts (individuals per L) of
Cyclops, Diaptomus, Daphnia, Epischura, Conochilus,
Non.daphnid.cladocerans and Non.colonial.rotifers.
lakeWAplanktonRaw in the MARSS package (Holmes et al.,
GPL-2), described there as adapted from the Lake Washington database
of W. T. Edmondson, funded by the Andrew Mellon Foundation, with data
courtesy of D. Schindler, University of Washington. See
help("lakeWAplankton", package = "MARSS") for the original
documentation and how to cite it.
lw <- lakewa_blocks() str(lw) fit <- lagged_protest(lw$Environment, lw$Zooplankton, lags = 0:3, nperm = 199, seed = 1) fit$optimal_laglw <- lakewa_blocks() str(lw) fit <- lagged_protest(lw$Environment, lw$Zooplankton, lags = 0:3, nperm = 199, seed = 1) fit$optimal_lag
Plots against lag. The dashed line is the alpha quantile of
the permutation null distribution at each lag (unadjusted); observed
values below it are significant at that level before correction. Filled
points mark lags whose p-value (adjusted, if p.adjust.method was not
"none") is below alpha. With global = TRUE, the optimal lag is
circled, filled when the global p-value is below alpha, and the global
p-value is printed above the plot; this is the p-value to report for the
optimal lag.
## S3 method for class 'lagged_protest' plot(x, alpha = 0.05, global = TRUE, ...)## S3 method for class 'lagged_protest' plot(x, alpha = 0.05, global = TRUE, ...)
x |
A |
alpha |
Significance level. |
global |
Logical; mark the optimal lag with its global p-value. |
... |
Further arguments passed to |
x, invisibly.
sim <- simulate_lagged_series(n_times = 36, true_lag = 2, noise_sd = 0.3, seed = 1) fit <- lagged_protest(sim$X, sim$Y, lags = 0:4, nperm = 199, seed = 1) plot(fit) plot(fit, alpha = 0.01, global = FALSE, main = "Lag profile")sim <- simulate_lagged_series(n_times = 36, true_lag = 2, noise_sd = 0.3, seed = 1) fit <- lagged_protest(sim$X, sim$Y, lags = 0:4, nperm = 199, seed = 1) plot(fit) plot(fit, alpha = 0.01, global = FALSE, main = "Lag profile")
Per-observation Procrustes residuals at the optimal lag
## S3 method for class 'lagged_protest' residuals(object, ...)## S3 method for class 'lagged_protest' residuals(object, ...)
object |
A |
... |
Unused. |
A data frame with the paired row labels of X and Y and the
residual of each pair after superimposition. Residuals are on the scale
of the configurations that were compared: after standardization
(scale = TRUE) and after any deseason or prewhiten step, not on
the scale of the original variables. They are not back-transformed.
sim <- simulate_lagged_series(n_times = 36, true_lag = 2, noise_sd = 0.3, seed = 1) fit <- lagged_protest(sim$X, sim$Y, lags = 0:4, nperm = 199, seed = 1) res <- residuals(fit) head(res) # Pairs that fit worst at the optimal lag res[order(res$residual, decreasing = TRUE)[1:3], ]sim <- simulate_lagged_series(n_times = 36, true_lag = 2, noise_sd = 0.3, seed = 1) fit <- lagged_protest(sim$X, sim$Y, lags = 0:4, nperm = 199, seed = 1) res <- residuals(fit) head(res) # Pairs that fit worst at the optimal lag res[order(res$residual, decreasing = TRUE)[1:3], ]
Generates X as a multivariate seasonal series plus AR(1) noise. Under
the null (true_lag = NULL), Y is an independent draw from the same
generator. Otherwise Y at time t is a linear map of X at time
t - true_lag plus AR(1) noise; X is generated over n_times + true_lag
points so that every row of Y has a source in X.
simulate_lagged_series( n_times = 24, n_vars_x = 5, n_vars_y = 5, true_lag = NULL, period = 12, amplitude = 1, waveform = c("circle", "sine", "harmonics", "sawtooth", "pulse"), spread = c("inphase", "anti", "random"), amp_sd_vars = 0, amp_sd_cycles = 0, autocorr = 0.5, noise_sd = 1, seed = NULL )simulate_lagged_series( n_times = 24, n_vars_x = 5, n_vars_y = 5, true_lag = NULL, period = 12, amplitude = 1, waveform = c("circle", "sine", "harmonics", "sawtooth", "pulse"), spread = c("inphase", "anti", "random"), amp_sd_vars = 0, amp_sd_cycles = 0, autocorr = 0.5, noise_sd = 1, seed = NULL )
n_times |
Number of time points (at least 3). |
n_vars_x, n_vars_y
|
Number of variables in |
true_lag |
|
period |
Length of the seasonal cycle, in time steps. |
amplitude |
Amplitude of the seasonal signal (that of an equivalent sinusoid for the non-sinusoidal waveforms). |
waveform |
Shape of the seasonal signal: |
spread |
Phase offsets of the variables around the block phase, for
every waveform except |
amp_sd_vars, amp_sd_cycles
|
Standard deviations of the log-normal
multipliers of the seasonal amplitude among variables and among cycles
of length |
autocorr |
AR(1) coefficient of the noise, in |
noise_sd |
Marginal standard deviation of the AR(1) noise. |
seed |
Optional integer seed. The global random number stream is left untouched. |
The seasonal component is set by waveform. The default, "circle",
gives every variable a sinusoid with a random phase common to the block
and offsets of among the variables. These
columns span a single plane with evenly spaced offsets, so the seasonal
configuration is a circle and a shift in time is an exact rotation of it,
which Procrustes analysis absorbs. Calibration estimated with this
generator is therefore a best case. The other waveforms break
this symmetry. Each variable follows the same periodic function, shifted
by an offset drawn around the block phase as set by spread:
"sine": ;
"harmonics": , with drawn once per block;
"sawtooth": a linear rise over the cycle followed by an abrupt drop;
"pulse": , a short peak once per cycle.
These waveforms are centered and scaled to the standard deviation of a
sinusoid of the same amplitude ( over a full
cycle), so that seasonal strength is comparable among them. When X and
Y share a non-sinusoidal waveform ("sawtooth" or "pulse"), phase
surrogates do not preserve the alignment of the harmonics within each
cycle, and the phase scheme of lagged_protest() can be strongly liberal
(see the article "Simulating lagged series").
Amplitudes can also vary among variables (amp_sd_vars) and among
successive cycles (amp_sd_cycles): each variable, or each cycle, has its
seasonal signal multiplied by . Both apply to
every waveform, including "circle".
Setting amplitude = 0 removes the seasonal component and leaves pure
AR(1) series; setting autocorr = 0 gives white noise around the
seasonal signal. The article "Simulating lagged series" shows how to use
the function for a calibration study.
A list with matrices X (n_times x n_vars_x) and Y
(n_times x n_vars_y), and true_lag.
null_pair <- simulate_lagged_series(n_times = 12, seed = 42) lagged_pair <- simulate_lagged_series(n_times = 24, true_lag = 3, seed = 42) str(lagged_pair) # Abrupt seasonality that varies in amplitude between years saw <- simulate_lagged_series(n_times = 36, waveform = "sawtooth", amp_sd_cycles = 0.3, noise_sd = 0.3, seed = 42) matplot(saw$X, type = "l", lty = 1, xlab = "Time", ylab = "X")null_pair <- simulate_lagged_series(n_times = 12, seed = 42) lagged_pair <- simulate_lagged_series(n_times = 24, true_lag = 3, seed = 42) str(lagged_pair) # Abrupt seasonality that varies in amplitude between years saw <- simulate_lagged_series(n_times = 36, waveform = "sawtooth", amp_sd_cycles = 0.3, noise_sd = 0.3, seed = 42) matplot(saw$X, type = "l", lty = 1, xlab = "Time", ylab = "X")
Summarize a lagged PROTEST
## S3 method for class 'lagged_protest' summary(object, ...) ## S3 method for class 'summary.lagged_protest' print(x, digits = 3, ...)## S3 method for class 'lagged_protest' summary(object, ...) ## S3 method for class 'summary.lagged_protest' print(x, digits = 3, ...)
object |
A |
... |
Unused. |
x |
A |
digits |
Number of significant digits to print. |
An object of class "summary.lagged_protest": the lag profile (a
data frame), with the optimal lag flagged in optimal. The scan-level
measures are attached as attributes: optimal_lag, p.global, effect
(lag of the largest z, Z, A and corrected RV) and ar1 (raw and
residual lag-1 autocorrelation of X and Y). Printing it shows the
profile followed by these measures; it can otherwise be used as a data
frame.
sim <- simulate_lagged_series(n_times = 12, true_lag = 2, noise_sd = 0.3, seed = 1) fit <- lagged_protest(sim$X, sim$Y, lags = 0:4, nperm = 199, seed = 1) s <- summary(fit) s attr(s, "effect")sim <- simulate_lagged_series(n_times = 12, true_lag = 2, noise_sd = 0.3, seed = 1) fit <- lagged_protest(sim$X, sim$Y, lags = 0:4, nperm = 199, seed = 1) s <- summary(fit) s attr(s, "effect")