Skip to contents

Converts irregularly spaced time series data — typical of Experience Sampling Method (ESM) / Ecological Momentary Assessment (EMA) studies — to a regular time grid using natural cubic spline interpolation.

The function automatically detects large temporal gaps in the signal and splits the data into contiguous subseries before interpolating, so that artefacts are not introduced across overnight breaks or missing assessment periods.

Usage

resample_timeseries(
  data,
  time_col = "time",
  participant_col = NULL,
  max_gap = 6,
  target_frequency = 60,
  interpolation_method = "spline",
  min_points = 4,
  verbose = TRUE,
  plot = TRUE,
  plot_offset = FALSE
)

Arguments

data

A data frame containing at minimum:

  • a timestamp column (identified by time_col);

  • one or more numeric variable columns — all numeric columns other than time_col and participant_col are treated as variables to interpolate (no specific naming convention is required);

  • optionally, a participant identifier column (identified by participant_col).

time_col

[character(1): "time"]
Name of the column in data that contains the timestamps. Values must be coercible to POSIXct.

participant_col

[character(1) or NULL: NULL]
Name of the column in data that identifies participants. If NULL (default), all observations are treated as coming from a single participant labelled "All".

max_gap

[numeric(1): 6]
Maximum allowable gap in hours between two consecutive observations before a new subseries is started. Gaps larger than this value (e.g., overnight breaks between daily bursts of notifications) mark a boundary between subseries.

target_frequency

[numeric(1): 60]
Desired spacing in minutes between consecutive observations on the regular output grid. For example, target_frequency = 60 produces one observation per hour; target_frequency = 30 produces one every 30 minutes.

interpolation_method

[character(1): "spline"]
Interpolation method to use. Either "spline" (natural cubic spline via stats::spline()) or "linear" (piecewise linear via stats::approx()). Both methods operate strictly within the range of valid (non-NA) observations — no extrapolation is performed beyond the data.

min_points

[integer(1): 4]
Minimum number of valid (non-NA) observations required within a subseries to attempt interpolation. Subseries with fewer points are silently dropped from the output.

verbose

[logical(1): TRUE]
If TRUE, prints a short processing summary to the console.

plot

[logical(1): TRUE]
If TRUE, a ggplot2::ggplot() object is built showing the interpolated time series (lines) overlaid with the original raw observations (crosses). Participants are distinguished by colour; multiple variables are shown in separate facets. The plot is stored as $plot in the returned object.

plot_offset

[logical(1): FALSE]
If TRUE, each subseries is shifted so that its x-axis starts at 0 (hours elapsed since the beginning of that subseries). This makes subseries and participants directly comparable regardless of their absolute timestamps.

Value

An object of class experdyn_resampled — a named list with:

ElementDescription
resampledData frame of interpolated observations (see below).
plotA ggplot object (or NULL if plot = FALSE).
interpolation_methodInterpolation method used ("spline" or "linear").
target_frequencyRequested spacing in minutes between observations.
sampling_rateAchieved rate in observations per hour (60 / target_frequency).
max_gapGap threshold in hours used for subseries detection.
n_participantsNumber of unique participants in the output.
n_subseriesTotal number of usable subseries.
n_points_rawNumber of rows in the input data.
n_points_resampledNumber of rows in resampled.
avg_points_per_participantMean resampled observations per participant.

The resampled data frame contains:

ColumnDescription
IDParticipant identifier.
Series_IDSubseries label "<ID>_<n>".
timeRegular grid timestamps (POSIXct).
<variable columns>Interpolated values, one column per numeric input variable.

Use print() for a human-readable summary, or access $resampled for the underlying data frame.

Details

Processing pipeline

Step 1 — Gap detection. For each participant, consecutive observations are compared. A new subseries is started whenever the gap exceeds max_gap (in hours). The subseries index is stored in Series_ID.

Step 2 — Spline interpolation. Within each qualifying subseries (at least min_points observations), each variable column is interpolated on a regular grid spaced at target_frequency minutes using the chosen interpolation_method (natural cubic spline or piecewise linear). Interpolation is strictly bounded to the range of valid observations — no extrapolation is performed. Grid points that fall outside this range, or where too many raw values are NA, are silently dropped.

Step 3 — Summary report. When verbose = TRUE, a brief table is printed showing the number of raw observations, interpolated observations, usable subseries, and the output sampling rate.

Why natural cubic splines?

Natural splines minimise the integrated squared second derivative subject to the constraint of passing through the data, which produces smooth interpolants without oscillatory artefacts at the boundaries. They are a standard choice for resampling physiological and psychological signals.

See also

  • stats::spline() for the underlying interpolation function.

  • The nonlinearTseries package for downstream complexity analyses.

Examples

# -----------------------------------------------------------------------
# Minimal synthetic ESM dataset
# Two participants, 15 irregular observations each, two variables
# -----------------------------------------------------------------------
set.seed(42)
n <- 15

# Irregular timestamps: gaps of 1, 1.5, 2, or 3 hours chosen at random
t_p1 <- as.POSIXct("2025-01-01 09:00:00") +
  cumsum(sample(60 * c(60, 90, 120, 180), n, replace = TRUE))
t_p2 <- as.POSIXct("2025-01-05 09:00:00") +
  cumsum(sample(60 * c(60, 90, 120, 180), n, replace = TRUE))

esm_data <- data.frame(
  Participant = c(rep("P01", n), rep("P02", n)),
  timestamp   = c(t_p1, t_p2),
  valence    = rnorm(2 * n),
  arousal    = rnorm(2 * n)
)

# Resample to a regular 60-minute grid — all numeric columns are used
result <- resample_timeseries(
  esm_data,
  time_col             = "timestamp",
  participant_col      = "Participant",
  target_frequency     = 60,
  verbose              = TRUE
)
#> --- Preprocessing Complete ---
#> Original data points    : 30
#> Interpolated data points: 52
#> Usable subseries        : 2
#> Output resolution       : 1 observation every 60 minutes
#> Sampling frequency      : 1 observations per hour
#> ------------------------------
result
#> ========= Resampled Time Series =========
#>   Sampling rate     : 1 obs/hour  (1 obs every 60 min)
#>   Gap threshold     : 6 hours
#>   Participants      : 2
#>   Subseries         : 2
#>   Raw obs           : 30
#>   Resampled obs     : 52  (avg 26.0 per participant)
#>   Data frame        : use `$resampled` to extract
#> =========================================
head(result$resampled)
#> # A tibble: 6 × 5
#>   ID    Series_ID time                valence arousal
#>   <chr> <chr>     <dttm>                <dbl>   <dbl>
#> 1 P01   P01_1     2025-01-01 10:00:00   0.636   0.433
#> 2 P01   P01_1     2025-01-01 11:00:00  -0.284  -0.811
#> 3 P01   P01_1     2025-01-01 12:00:00  -2.66    1.44 
#> 4 P01   P01_1     2025-01-01 13:00:00  -2.44   -0.431
#> 5 P01   P01_1     2025-01-01 14:00:00   0.120  -0.130
#> 6 P01   P01_1     2025-01-01 15:00:00   1.97    1.22 

# -----------------------------------------------------------------------
# Single-participant usage (participant_col = NULL)
# -----------------------------------------------------------------------
single <- data.frame(
  timestamp   = t_p1,
  valence     = rnorm(n)
)
result_single <- resample_timeseries(
  single,
  time_col            = "timestamp",
  target_frequency    = 30,
  verbose             = FALSE
)

# -----------------------------------------------------------------------
# Stricter gap threshold: split on gaps > 4 hours
# -----------------------------------------------------------------------
resampled_strict <- resample_timeseries(
  esm_data,
  time_col            = "timestamp",
  participant_col     = "Participant",
  max_gap             = 4,
  target_frequency    = 30,
  verbose             = FALSE
)
# Note: more (shorter) subseries are detected
length(unique(resampled_strict$resampled$Series_ID))
#> [1] 2

# -----------------------------------------------------------------------
# Arbitrary column names — no "Component_" prefix required
# -----------------------------------------------------------------------
esm_custom <- data.frame(
  id        = c(rep("P01", n), rep("P02", n)),
  ts        = c(t_p1, t_p2),
  stress    = rnorm(2 * n),
  energy    = rnorm(2 * n)
)
result_custom <- resample_timeseries(
  esm_custom,
  time_col        = "ts",
  participant_col = "id",
  verbose         = FALSE
)