---
title: "Asynchronous Longitudinal Regression"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Asynchronous Longitudinal Regression}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 4
)
```

```{r setup, message = FALSE, warning = FALSE}
library(skmle)
```

The two data frames come first in every call, so the estimators compose with
the native pipe. Examples below use it where it reads better.

## The problem

Suppose you want to know how a biomarker relates to a symptom score. The
biomarker is drawn at clinic visits; the symptom score is collected by a
questionnaire on its own schedule. Neither is measured often, and the two
schedules have nothing to do with each other. You have, per subject,

- a response process $Y_i(\cdot)$ observed at times $T_{i1}, \dots, T_{iL_i}$,
- a covariate process $X_i(\cdot)$ observed at times $S_{i1}, \dots, S_{iM_i}$,

and $\{T_{ij}\}$ and $\{S_{ik}\}$ never coincide. The model you want is the
ordinary one,

$$E\{Y_i(t) \mid X_i(t)\} = g\{X_i(t)^\top \beta\},$$

but $Y_i$ and $X_i$ are never observed at the same $t$, so not one row of the
data set is a complete observation of the regression you are trying to fit.

This is the setting of Cao, Zeng and Fine (2015). The package implements their
two estimators: `kee_async()` for a constant $\beta$, and `kee_async_td()` for
a coefficient curve $\beta(t)$.

Carrying the last covariate value forward, or smoothing the covariate first and
substituting it, both attenuate $\hat\beta$ when sampling is sparse. The
kernel-weighted equation instead evaluates the link at each covariate vector
you actually have, and lets a weight express how much that observation says
about a given response occasion.

## The estimator

$$U_n(\beta) = n^{-1} \sum_i \sum_j \sum_k W_h(T_{ij} - S_{ik})\,
  X_i(S_{ik}) \left[ Y_i(T_{ij}) - g\{X_i(S_{ik})^\top \beta\} \right] = 0,$$

with $W_h(u) = W(u/h)/h$ and $W$ the Epanechnikov kernel. Every
(response, covariate) pair within a subject contributes, weighted by how far
apart in time the two occasions are. Pairs more than $h$ apart drop out; pairs
close together dominate.

The equation sees times only through $(T - S)/h$, so any units work as long as
`h` is in the same ones. The package warns when it looks wrong.

## A worked example

`sim_async_data()` generates the design from Section 4 of the paper: response
and covariate observation times are independent Poisson streams, and the
covariate is a Gaussian process.

```{r sim}
set.seed(2024)
d <- sim_async_data(n = 400, beta = c(0.5, 1.5))

str(d$y)
str(d$x)
```

Two tables, sharing only `id`. There is no way to merge them without inventing
rows, which is precisely the point.

```{r counts}
c(
  subjects = length(unique(d$y$id)),
  response_occasions = nrow(d$y),
  covariate_occasions = nrow(d$x),
  median_per_subject_y = median(table(d$y$id)),
  median_per_subject_x = median(table(d$x$id))
)
```

The formula spans both tables, taking its left-hand side from `data_y` and its
right-hand side from `data_x`. `id` and `time` name columns present in each:

```{r fit}
fit <- d$y |>
  kee_async(d$x, y ~ x, id = id, time = time, h = 0.25)

summary(fit)
```

The truth is $\beta = (0.5, 1.5)$. `npair` records how many weighted pairs
actually contributed:

```{r npair}
c(pairs = fit$npair, subjects = nobs(fit))
```

Standard generics work as usual:

```{r generics}
coef(fit)
confint(fit)
sqrt(diag(vcov(fit)))
```

## Tidy output

`tidy()`, `glance()` and `augment()` return tibbles, so a fit goes straight into
the rest of a tidy workflow without reshaping.

```{r tidy}
tidy(fit, conf.int = TRUE)

glance(fit)
```

`augment()` attaches the fitted mean to the **covariate** table, because that is
where a fitted value lives here: the estimating equation evaluates the link at
each observed covariate vector, and the kernel weight is what ties that vector
to a response occasion.

```{r augment}
augment(fit, d$x)
```

The fit does not retain its data, so `augment()` needs
`data_x` handed back to it.

## Choosing the bandwidth

`h` is in the units of `time`. Small `h` admits few pairs; large `h` admits
pairs far apart in time. Fit at several values and compare:

```{r sweep, fig.height = 3.5}
hs <- c(0.05, 0.10, 0.15, 0.25, 0.40, 0.60)
sweep <- t(sapply(hs, function(h) {
  f <- d$y |> kee_async(d$x, y ~ x, id = id, time = time, h = h)
  c(h = h, est = coef(f)[2], se = sqrt(vcov(f)[2, 2]))
}))
round(sweep, 3)

plot(sweep[, "h"], sweep[, 2],
  type = "b", pch = 19, ylim = range(sweep[, 2] + c(-2, 2) * sweep[, 3]),
  xlab = "bandwidth h", ylab = expression(hat(beta)[1]),
  main = "Estimate against bandwidth"
)
arrows(sweep[, "h"], sweep[, 2] - 1.96 * sweep[, 3],
  sweep[, "h"], sweep[, 2] + 1.96 * sweep[, 3],
  angle = 90, code = 3, length = 0.04, col = "grey50"
)
abline(h = 1.5, lty = 2, col = "firebrick")
```

Choose `h` from this plot, weighing the width of the interval against how far
the estimate moves.

## Half kernel or full kernel

By default the kernel is two-sided: a response at $T_{ij}$ is informed by
covariate observations on either side of it. If the covariate must be *already
known* at the response time, whether for a causal reading or because later
covariate values could not have influenced the response, set
`one_sided = TRUE`.

```{r half}
full <- kee_async(d$y, d$x, y ~ x, id = id, time = time, h = 0.25)
half <- kee_async(d$y, d$x,
  y ~ x, id = id, time = time,
  h = 0.25, one_sided = TRUE
)

rbind(
  full = c(coef(full), pairs = full$npair),
  half = c(coef(half), pairs = half$npair)
)
```

The half kernel discards roughly half the pairs, so at a fixed `h` it is noisier.
Compare bandwidths under the same setting you intend to fit with.

## Time-varying coefficients

If the association itself changes over follow-up, `kee_async_td()` estimates
$\beta(t)$ pointwise. At a target time $t$ the response and covariate occasions
are weighted by their **separate** distances to $t$; the lag between them never
enters.

$$U_n\{\beta(t)\} = n^{-1} \sum_i \sum_j \sum_k W_{h_1}(t - T_{ij})\,
  W_{h_2}(t - S_{ik})\, X_i(S_{ik})
  \left[ Y_i(T_{ij}) - g\{X_i(S_{ik})^\top \beta(t)\} \right] = 0.$$

Both time arguments are smoothed, so the curve needs more data than the
time-invariant fit.

```{r td, fig.height = 4}
set.seed(2025)
dt <- sim_async_data(
  n = 800, beta = function(tt) cbind(0.5, 1 + tt),
  lambda_y = 8, lambda_x = 8,
  x_cov = function(s, t) exp(-4 * (s - t)^2)
)

fit_td <- kee_async_td(dt$y, dt$x,
  y ~ x, id = id, time = time,
  times = seq(0.2, 0.8, by = 0.05), h = 0.2
)
plot(fit_td)
```

The truth is $\beta_1(t) = 1 + t$. Compare the fitted curve against it:

```{r td-truth}
tidy(fit_td, conf.int = TRUE) |>
  subset(term == "x", select = c(time, estimate, conf.low, conf.high)) |>
  head(4)
```

The bands are pointwise. Keep `times` inside the observed time range.

## Links other than the identity

`link = "log"` and `link = "logistic"` fit the corresponding generalised linear
models by Newton-Raphson on the same estimating equation. Everything above
applies unchanged.

```{r logistic}
set.seed(11)
db <- sim_async_data(n = 400, beta = c(0.3, 1.0), link = "logistic")
fit_b <- kee_async(db$y, db$x,
  y ~ x,
  id = id, time = time, h = 0.3, link = "logistic"
)
summary(fit_b)
```

## Getting the units right

`h` must be on the same scale as the observation times. With times in days
and `h` chosen as though they were on the unit interval, the package warns that
almost nothing is contributing.

```{r units, warning = TRUE}
d_days <- d
d_days$y$time <- d$y$time * 365
d_days$x$time <- d$x$time * 365

fit_days <- kee_async(d_days$y, d_days$x,
  y ~ x,
  id = id, time = time, h = 1
)
```

Rescaling `h` by the same factor recovers the original fit exactly, which is the
scale-equivariance of the estimating equation:

```{r units-fixed}
fit_ok <- kee_async(d_days$y, d_days$x,
  y ~ x,
  id = id, time = time, h = 0.25 * 365
)
all.equal(coef(fit_ok), coef(fit))
```

The survival estimators behave the same way. Their spline basis and
cumulative-hazard quadrature are built on the observed follow-up rather than a
fixed interval, so rescaling time and the bandwidth together leaves the
coefficients unchanged.

## Reference

Cao, H., Zeng, D. and Fine, J. P. (2015). Regression analysis of sparse
asynchronous longitudinal data. *Journal of the Royal Statistical Society,
Series B* **77**, 755–776.
