(De)Trends

Packages: dplyr, tidyr, ggplot2, zoo, Kendall, tseries

Trends are defined as a change in the mean of the process over time. It is critical in time series analysis as it violates the stationarity assumption (i.e., xxx) which is a common and strong assumption of longitudinal models (e.g., autoregressive models). From this violation can return a bias and/or a decrease in precision in the estimated parameters and, consequently, less reliable statistical inference. Rather than an issue to deal with or a source of noise hindering model and interpretation, trends are an important piece of information; it is an inherent part of the participants’ dynamics that deserves consideration. Indeed, trends can be induced by the design or expected from the participants’ dynamics. For instance, we can expect that a successful treatment to prevent relapse from depression would translate to potential trends in depression symptoms or related variables (e.g., negative affects). In this context, trends deserve to be modeled and tested. Furthermore, this important piece of information can also help to select an adapted model. For instance, a time series that present switches between two process dynamics that seems to be stable around a mean each (e.g., xxx), this can indicate the needs of using regime-switching models (REFxxx). Finally, actual stationary processes can resemble trends. For instance, a high autoregressive process (e.g., ar=.9) can give the feeling that the time series capture contains a trend (see Visualization sub-section). Although trends sound like a simple phenomenon, they hide a profound complexity that hinders the capacity to detect and deal with them. Part of this is due to the many shapes that trends can take. They are often categorized into different groups:

Deterministic trends. The trend follows a fixed mathematical function (linear or non-linear) dependent on time. In case of a linear trend, it can be either upward (increasing) or downward (decreasing). Given their linear association with time, they are rather easy to investigate. In a linear model, this can be expressed as: \(Y_{t} = \beta_{0} + \beta_{1} * t + \sigma_t\) where \(t\) is the time index. Although, deterministic trends can also be non-linear such as quadradic (\(Y_{t} = \beta_{0} + \beta_{1} * t^2 + \sigma_t\)), exponential (\(Y_{t} = \beta_{0} + \text{exp}(\beta_{1} * t) + \sigma_t\)), or polynomial of different degrees.

Stochastic trends. It is a trend that has a random component that linger over time, affecting the long-term trajectory of the time series. Hence, this make this trend cannot be capture by a fixed mathematical function, making it even further challenging.

Consider this tutorial only as an introduction. It does not pretend to solve the trend issues in ESM studies. In particular:

  • we will mainly focus on detecting deterministic trends and providing some thoughts on how to deal with them. - importantly, trends detection or implication for models must be checked in the residuals of the model. This is an important practice that should be systematically considered.
  • While this tutorial focus on univariate time series (e.g., positive affect trajectory of one participant), detecting trends in multilevel data requires further considerations. We provide a short discussion on this topic in the Multilevel Consideration sub-section.

Detection Methods (N=1)

We provide three methods to detect trends: visualization, statistical test, and regression-based methods.

Visualization

The most straightforward approach to detect trends is through visualization, which is easy in R. Here, we specifically investigate the trend in the ‘PA1’ time series of the xxx participant. Two options are available: using (1) the base R ‘plot’ function and (2) the ggplot2 package.

plot(
    x = data[data$id == 2, ]$obsno, 
    y = data[data$id == 2, ]$PA1,
    type = "b"
)

To highlight potential trends, different features can be added to the plot. In particular, a smoothed time series can reveal underlying trends by reducing noise and random fluctuations. Importantly, ESM data contains missing values that can hinder the smoothing process. To deal with this issue, one can impute or interpolate the missing values before applying smoothing. We provide different methods (e.g., linear interpolation, spline interpolation, and forward/backward fill) that can influence the results, with the more missing values, the more the imputation will influence the results. Hence, it is important to consider which method is the most appropriate for your data.

  • LOWESS (Locally Weighted Scatterplot Smoothing): xxx.
    • R base: To deal with missing values, we propose to fit lowess on the complete cases and then interpolate the fitted values back to the full time range. This second step is done using the ‘approx’ function. This function performs linear interpolation between the fitted values to fill in the gaps: when there are missing values in the original data, it drawns straight lines between the nearest LOWESS points.
    • ggplot2: The ‘geom_smooth’ function can be used to add a LOWESS smooth to the plot and has a build-in function to deal with missing values. The ‘span’ parameter controls the degree of smoothing: a smaller value results in less smoothing, while a larger value results in more smoothing. The default is 0.75, but you can adjust it to your preference.

# Create function to generate LOWESS smoothed values and interpolate
lowess_interp <- function(series, time_index, f = 0.2, rule = 2) {
  # Select complete cases
  complete_cases <- !is.na(series)
  time_complete <- time_index[complete_cases]
  series_complete <- series[complete_cases]

  # Fit lowess on complete cases
  lowess_fit <- lowess(time_complete, series_complete, f = f)

  # Interpolate lowess fitted values back to the full time range
  lowess_interpolated <- approx(lowess_fit$x, lowess_fit$y, 
                               xout = time_index, rule = rule)
  
  return(lowess_interpolated)
}

# Filter data for participant 1
data_id2 <- data[data$id == 2, ]

# Create time index (assuming observations are in chronological order)
time_index <- 1:nrow(data_id2)

# Generate LOWESS smoothed values and interpolate
lowess_interpolated <- lowess_interp(data_id2$PA1, time_index)

# Plot original data and LOWESS smooth
plot(time_index, data_id2$PA1, type = "l", col = "black")
lines(lowess_interpolated$x, lowess_interpolated$y, col = "red", lwd = 2)
legend("topright", legend = c("Original", "LOWESS"), 
       col = c("black", "red"), lty = 1, lwd = c(1, 2))

  • Moving average: it is defined following a time windows: xxx. Different time windows can be used, such as 5, 10 or 20. To deal with missing values, we propose different methods. The standard moving average (1) returns NA if any value in the window is NA. Hence, if time series contains a lot of missing values, the moving average will be very sparse. The partial moving average (2) uses only the available values in the window xxx. The moving average after linear interpolation (3), which first interpolates the missing values and then applies the moving average. While we demonstrate how to perform those three methods, you can select the one that best fits your needs. Beyond this three methods, we propose two implementations:
    • R base: The ‘zoo’ package provides the ‘rollmean’ function to compute the moving average, and the ‘na.approx’ function can be used for linear interpolation.
    • ggplot2: The ‘geom_smooth’ function can also be used to add a moving average to the plot. The ‘method = “loess”’ option can be used for local polynomial regression fitting, which is similar to a moving average. However, it does not directly support missing values, so we need to handle them separately before plotting.

Base R
ggplot2
# Filter data for participant 2
data_id2 <- data[data$id == 2, ]
# Create time index
time_index <- 1:nrow(data_id2)

# Calculate moving averages with different windows
window_size <- 10  # You can change this to 5, 10, or 20

# Standard moving average (NA if any value in window is NA)
ma_standard <- zoo::rollmean(data_id2$PA1, k = window_size, fill = NA, align = "center")

# Plot original data and moving average
plot(time_index, data_id2$PA1, type = "l", col = "black")
lines(time_index, ma_standard, col = "blue", lwd = 2)
legend("topright", legend = c("Original", paste("Standard MA", window_size)),
       col = c("black", "blue"), lty = 1, lwd = c(1, 2))

Given trends can take multiple shapes, it is important to visualize the time series through different setting values. For instance, we can assemble different moving averages values with the loess smoothing. Altogether in a plot or in panels.

Base R
ggplot2
# Create partial moving average function
partial_rollmean <- function(x, k, align = "center") {
  n <- length(x)
  result <- rep(NA, n)
  if (align == "center") {
    half_window <- floor(k/2)
    for (i in 1:n) {
      start <- max(1, i - half_window)
      end <- min(n, i + half_window)
      window_vals <- x[start:end]
      if (sum(!is.na(window_vals)) > 0) {
        result[i] <- mean(window_vals, na.rm = TRUE)
      }
    }
  }
  return(result)
}

# Filter data for participant 2
data_id2 <- data[data$id == 2, ]
time_index <- 1:nrow(data_id2)

# Calculate different moving averages
ma_5 <- partial_rollmean(data_id2$PA1, k = 5, align = "center")
ma_10 <- partial_rollmean(data_id2$PA1, k = 10, align = "center")
ma_20 <- partial_rollmean(data_id2$PA1, k = 20, align = "center")

# LOWESS smoothing
lowess_interp <- function(series, time_index, f = 0.2, rule = 2) {
  complete_cases <- !is.na(series)
  time_complete <- time_index[complete_cases]
  series_complete <- series[complete_cases]
  lowess_fit <- lowess(time_complete, series_complete, f = f)
  lowess_interpolated <- approx(lowess_fit$x, lowess_fit$y,
                               xout = time_index, rule = rule)
  return(lowess_interpolated)
}
lowess_smooth <- lowess_interp(data_id2$PA1, time_index)

# Plot all methods together
plot(time_index, data_id2$PA1, type = "l", col = "black")
lines(time_index, ma_5, col = "red", lwd = 2)
lines(time_index, ma_10, col = "blue", lwd = 2)
lines(time_index, ma_20, col = "green", lwd = 2)
lines(lowess_smooth$x, lowess_smooth$y, col = "purple", lwd = 2)
legend("topright", 
       legend = c("Original", "MA 5", "MA 10", "MA 20", "LOWESS"),
       col = c("black", "red", "blue", "green", "purple"), 
       lty = 1, lwd = c(1, 2, 2, 2, 2))

However, this approach comes with limitations. It is not always easy to differentiate between an actual trend and a stochastic process (no trend). For instance, the time series on Panel A is a autoregressive process (ar=xxx), while the one in Panel B contains a xxx trend and the one on the right. Additionally, trends sometimes need to be revealed with an adapted sampling scheme (Panel C) and sample size (Panel D).

Statistical Tests

Many statistical tests can detect trends. These can be categorized into non-parametric tests (e.g., Mann-Kendall test) or Unit Root tests (e.g., Augmented Dickey-Fuller). As the first group focuses on detecting monotonic trends, the second group tests for stochastic non-stationarity. While we introduce only two tests for conciseness consideration, readers can refers to REFxxx for a review.

Mann-Kendall Test. This method run an hypothesis test to test if the time series follows a monotonic trend (i.e., a constant upward or downward trend) without making assumptions regarding the data distribution (e.g., normality). If \(H_0\) is rejected (typically if \(p < .05\)) then the time series contains a monotonic trend (upward or downward). An additional statistics, S, indicate if this is a upward (positive S) of downward (negative S) trend.

library(Kendall)
result <- MannKendall(data[data$id == 2, "PA1"]) 
summary(result)
Score =  731 , Var(Score) = 17956.33
denominator =  1425.991
tau = 0.513, 2-sided pvalue =< 2.22e-16

Augmented Dickey-Fuller (ADF) Test. This statistical test informs if the time series contains a stochastic trend, specifically testing if an Unit Root compose the time series. If \(H_0\) is not rejected (typically if \(p >= .05\)), this indicates that the time series contains a stochastic trends. Hence, the significance test would be positive if the time series has no stochastic trend. Importantly, it is required to deal with missing values such as through interpolation or imputation. Here, we use the ‘na.approx’ function from the ‘zoo’ package to perform linear interpolation. The ADF test is then applied to the interpolated time series. However, it is important to note that this might impact the results, especially if the time series contains a lot of missing values.

library(tseries) 
data_id2 <- data[data$id == 2, ] # Filter data for participant 2
pa1_interpolated <- na.approx(data_id2$PA1, na.rm = FALSE)
adf_result <- adf.test(pa1_interpolated, alternative = "stationary") 
print(adf_result)

    Augmented Dickey-Fuller Test

data:  pa1_interpolated
Dickey-Fuller = -2.7916, Lag order = 4, p-value = 0.2533
alternative hypothesis: stationary

However, keep in mind that those tests also have limitations, often testing for simple trend tendencies, ignoring the other ones. For instance, the Mann-Kendall test would ignore quadratic trends.

Regression-Based Methods

Trend detection can also be done through linear models. The basic idea is to implement the observation number (obsno) as a predictor variable in a regression model, hence directly modeling the relationship between time and the observed values. Although straightforward, this approach is not ideal. Beyond typical regression assumptions (e.g., sensitivity to outliers), the shape of the trend is assumed not to change over the time series and, importantly, must be pre-specified in the model (e.g., quadratic). If multiple shapes are expected, they must be tested one after the other.

Linear trend models. The simplest trend shape to investigate is linear upward or downward. This can be performed by simply incorporating the observation number (obsno) in the model. In this model, the parameter associated with obsno provide information regarding the direction of the bias (upward if beta > 0 and downward if beta < 0) and the magnitude of the bias. If the hypothesis test associated is significant, then it asserts that a trends compose the time series.

data_id2 <- data[data$id == 2, ] # Filter data for participant 2
# Fit linear trend model 
trend_model <- lm(PA1 ~ obsno, data = data_id2) 
summary(trend_model)

Call:
lm(formula = PA1 ~ obsno, data = data_id2)

Residuals:
    Min      1Q  Median      3Q     Max 
-17.290  -6.519  -0.862   6.126  20.433 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 20.21836    2.32211   8.707 9.89e-12 ***
obsno        0.45178    0.05707   7.917 1.72e-10 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 8.795 on 52 degrees of freedom
  (16 observations deleted due to missingness)
Multiple R-squared:  0.5465,    Adjusted R-squared:  0.5378 
F-statistic: 62.68 on 1 and 52 DF,  p-value: 1.723e-10

Polynomial trend modeling. When the trend is not linear but follows a more complex pattern, polynomial terms can be incorporated into the model. This approach is appropriate to detect accelerating or decelerating trends, reversals, U-shape, or other non-linear patterns. Those can be modeled through higher-order terms of the observation number. It results: y = β₀ + β₁(obsno) + β₂(obsno²) + β₃(obsno³) + … + βₙ(obsnoⁿ) + ε Each coefficient represents different aspects of the trend: β₁ indicates the linear component, β₂ the quadratic component (acceleration/deceleration), β₃ the cubic component (changes in acceleration), and so on. The significance of these terms determines the complexity of the trend pattern. However, the higher the order is, the more flexible the model is, and the higher the risk is of overfitting the data. Consequently, researchers must consider which highest order is still relevant/plausible and maybe employ model selection metrics to better inteprete the results. This must also be in regards to the sample size. The higher the order of the trend, the more sample size are needed, making it unrealistic to, for instance, investigate cubic effect in time series of 10 measurements.

CODE

Polynomial detection makes the interpretation of the trends more nuanced. A significant quadratic term indicate a conclave downward bias (if beta < 0; initially increasing then decreasing) and a concave upward curve (if beta > 0; initially decreasing then increasing). The cubic term would represent more complex S shape. See the plot for the interpretation of the different order terms: PLOT

Detrending Methods (N=1)

Many models assume stationarity, leading researchers to detrend their time series before analysis. If non-stationarity stems solely from trends, detrending will restore stationarity and make the process suitable for these models. However, when a time series violates stationarity for multiple reasons (e.g., trends + seasonality), applying only the detrending method will make the time series closer to stationarity, but not completely stationary. Remember that trends are substantial information about the process under-studied. It should not be just ignored and any detrending operation must be justified, reported, and integrated in how the model output is interpreted. In sum, detrending (if applied) are an essential component of the modeling approach undertaken.

Variable transformation

Differencing. It removes trends by computing the change between consecutive observations: \(\Delta Y_t = Y_t - Y_{t-1}\). This transformation is specifically designed for stochastic trends. Often, a first-order differencing is used, however, more complex trends (e.g., quadradic) requires higher-order differencing such as order two: \(\Delta^2 Y_t = \Delta Y_t - \Delta Y_{t-1} = Y_t - 2Y_{t-1} + Y_{t-2}\). CODE

Modeling approaches

Modeling approaches to detrending involve explicitly incorporating trend components into the statistical model rather than transforming the data. This has the advantage of preserving the original data structure while allowing for hypothesis testing about trend parameters. The most common approach is regression-based detrending, where the trend is modeled as a function of time and then subtracted from the original data. This method is particularly useful when you want to understand the nature of the trend (linear, quadratic, etc.). Multiple trend patterns can be tested one against the other. Linear. For instance, in an AR(1) model, time is modeled by adding a new parameter (\(xxx\)). CODE

Polynomial.

Check your residuals

Checking residuals is a crucial step, whatever you choose to detrend or not your time series. Indeed, trends can also be investigated in the model residuals, mainly through visualization. In this context, residual analysis serves multiple purposes: (1) it validates the effectiveness of your detrending procedure, (2) it reveals whether additional polynomial terms or alternative detrending methods are needed, and (3) it ensures that subsequent analyses (e.g., autoregressive modeling) are performed on stationary data. Checking model residuals. CODE

Advanced topics

Multilevel considerations

ESM studies often collect data across many participants, meaning that the collected data is multilevel. However, trend detection becomes more complex because trends can occur at different levels: individual-level trends, group-level trends, or both. In other words, participants from the same or different groups can share or exhibit different trend patterns. Adding to the inherent complexity of trends on single time series, this hierarchical structure makes the detection and the treatment of trends challenging. Researchers exploring this concern in ESM fall short and are more than required. In this context, visualization and model-based approaches are probably the most cautious approach. After a visual investigation of (systematic) trends among the participants in the data, one can use a multilevel model-based approach with a random effect to account for and test for simple linear trends. Visual inspection. The idea here is to extend the plots presented in the Visualization Section to investigate multiple participants altogether. Note that you will probably need to make iteratively visualization of sub-sample of your participants: not all participants will fit into one plot. CODE

Modeling approaches. Building on the Modeling approaches section, an fixe parameter with random effect can be added to a multilevel model. Here is an example of a multilevel autoregressive model where \(xxx\) is added. In the model outputs, you can investigate is the fixed parameter for linear trend is significant, and what are the different trend parameter (random parameters) for each participant.

2+ variables

TODO Cointegration analysis can identify whether multiple variables share long-term trending relationships, while Vector Error Correction Models (VECM) can model these shared trends explicitly.

Regime-switching

TODO

References

Ryan non-stationarity in time series analysis: distinguishing trend