knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  warning = FALSE,
  message = TRUE,
  out.width = "100%"
)

Data preparation

laggedcor needs two time-series data and their corresponding time.

The demo data can be from laggedcor.

library(laggedcor)
data("step_data", package = "laggedcor")
data("heart_data", package = "laggedcor")

head(step_data)
head(heart_data)
time_plot(x = step_data$step, time = step_data$time)
time_plot(x = heart_data$heart, time = heart_data$time)

Calculate lagged correlation

Then we calculate the lagged correlations between step and heart rate.

dim(step_data)
dim(heart_data)

The time-series data with less number of time point should be set as x.

x = step_data$step
time1 = step_data$time

y = heart_data$heart
time2 = heart_data$time
start_time <- Sys.time()

result <-
  calculate_lagged_correlation(
    x = x,
    y = y,
    time1 = time1,
    time2 = time2,
    time_tol = 0.2,
    step = 2 / 60,
    min_matched_sample = 10,
    threads = 16,
    cor_method = "spearman"
  )

end_time <- Sys.time()
end_time - start_time

The parameters of calculate_lagged_correlation;

Result of lagged correlation

result
saveRDS(result, "lagged_correlation_result.rds")

We can see that the index of max correlation is 11 and index of global correlation is 12, means that the max correlation is achieved from a shifted time.

Result of lagged correlation

extract_max_cor(object = result)
extract_global_cor(object = result)

We can see that when the shift time is "(-1.5,-0.5]", we get the max correaltion: 0.58. This means x (step) changes before y (heart rate).

extract_all_cor(result)
extract_all_cor_p(result)
extract_shift_time(result, numeric = TRUE)
extract_shift_time(result, numeric = FALSE)

Evaluate the quality of lagged correlation

evaluate_lagged_cor(object = result, plot = TRUE)

Some results

lagged_scatter_plot(object = result, hex = TRUE, which = "global")
lagged_scatter_plot(object = result, hex = TRUE, which = "max")
lagged_alignment_plot(object = result, which = "global", x_limit = c(1,50000))


jaspershen/laggedcor documentation built on June 10, 2025, 5:42 p.m.