Package 'skmle'

Title: Sieve Maximum Kernel-Weighted Log-Likelihood Estimation
Description: Estimation and inference when a longitudinal covariate is observed sparsely and intermittently, at times that do not line up with the times at which the outcome is measured. For a survival outcome, fits the transformed hazards family -- proportional hazards, additive hazards, and the Box-Cox transformations between them -- by the Sieve Maximum Kernel-weighted Log-likelihood Estimator (SMKLE) of Sun, Sun, Zhao and Cao (2025) <doi:10.1080/01621459.2025.2476781>, with specialised kernel estimating-equation alternatives for the proportional and additive cases. For a longitudinal outcome recorded on its own time grid, fits generalised linear models by the kernel-weighted estimating equations of Cao, Zeng and Fine (2015) <doi:10.1111/rssb.12086>, with either time-invariant or time-dependent coefficients. Half and full kernels, data simulation, and bandwidth selection by cross-validation are available throughout, and the numerical routines use 'Rcpp', 'RcppArmadillo' and the 'nloptr' C API.
Authors: Dayu Sun [aut, cre, cph]
Maintainer: Dayu Sun <[email protected]>
License: MIT + file LICENSE
Version: 0.1.0
Built: 2026-12-05 20:01:34 UTC
Source: https://github.com/cran/skmle

Help Index


Add fitted means to the covariate table

Description

Fitted means belong to covariate occasions. The estimating equation evaluates the link at each observed covariate vector, and the kernel weight is what ties that vector to a response occasion. So augment() returns data_x with a .fitted column, g(Xi(Sik)⊤β^)g(X_i(S_{ik})^\top \hat\beta).

Usage

## S3 method for class 'kee_async'
augment(x, data_x, ...)

Arguments

x

A kee_async fit.

data_x

The covariate table the fit was made from.

...

Unused.

Details

The fit does not retain its data, so data_x must be supplied.

Value

data_x as a tibble with a .fitted column added.

Examples

set.seed(1)
d <- sim_async_data(n = 150)
fit <- kee_async(d$y, d$x, y ~ x, id = id, time = time, h = 0.3)
augment(fit, d$x)

Wald confidence intervals for a coefficient curve

Description

Pointwise Wald intervals at each target time.

Usage

## S3 method for class 'kee_td'
confint(object, parm, level = 0.95, ...)

Arguments

object

A kee_td object.

parm

Coefficients to report, by name or position. Defaults to all.

level

Confidence level.

...

Unused.

Details

For skmle and kee fits no method is needed: stats::confint.default() works once vcov() is available.

Value

A data frame with one row per (target time, coefficient) and columns time, term, estimate, se, and the two interval endpoints.

Examples

set.seed(1)
d <- sim_async_data(n = 200, beta = function(tt) cbind(0.5, 1 + tt))
fit <- kee_async_td(d$y, d$x,
  y ~ x, id = id, time = time,
  times = c(0.3, 0.5, 0.7), h = 0.3
)
confint(fit)

One-row summary of a fit

Description

One-row summary of a fit

Usage

## S3 method for class 'skmle'
glance(x, ...)

## S3 method for class 'kee'
glance(x, ...)

## S3 method for class 'kee_td'
glance(x, ...)

Arguments

x

A fitted skmle, kee or kee_td object.

...

Unused.

Value

A one-row tibble. nobs is the number of subjects.

Examples

set.seed(1)
d <- sim_async_data(n = 150)
fit <- kee_async(d$y, d$x, y ~ x, id = id, time = time, h = 0.3)
glance(fit)

Fit an Additive Hazards KEE Model

Description

Fit the additive hazards model for sparse longitudinal covariate data using a kernel estimating-equation approach.

Usage

kee_additive(
  formula,
  data,
  id,
  obs_times,
  h = NULL,
  lq_nodes = 64,
  one_sided = TRUE,
  weight = NULL
)

Arguments

formula

A model formula with a survival::Surv() response.

data

Data frame containing all variables used in the fit.

id

Subject identifier aligned row-wise with data.

obs_times

Longitudinal observation times aligned row-wise with data. Times may be on any scale; the cumulative-hazard quadrature is built on the observed follow-up, so there is no need to rescale to the unit interval first. h must be on the same scale. Observation times may be negative; see “Negative observation times” in kee_cox().

h

Positive kernel bandwidth. If omitted, one is read off the observation times as a rule of thumb and reported in a message. Use skmle_cv() to choose it from the data.

lq_nodes

Number of quadrature nodes used in the numerical integration step.

one_sided

Logical. TRUE (the default) uses a half kernel: only covariate observations strictly before the event or quadrature time inform that time, which is the risk-set restriction and the estimator as published. FALSE uses a full, two-sided kernel, smoothing the covariate path from both sides. The switch applies to the risk-set averages inside the C++ backend as well as to the row weights, so the two are always consistent.

weight

Weight function of the standardised lag (t−r)/h(t - r)/h, or NULL (the default) for the Epanechnikov kernel implied by one_sided. Any R function will do; see kernel-weights.

Details

kee_additive() is the specialized additive-hazards counterpart to kee_cox(). It uses a kernel-smoothed martingale estimating equation and typically runs faster than the general skmle(s = 1) fit because it solves a more specialized problem.

Value

An object of class kee containing coefficient estimates, an estimated variance-covariance matrix, intermediate matrices used for sandwich variance estimation, and model metadata.

References

Sun, Dayu, Zhuowei Sun, Xingqiu Zhao, and Hongyuan Cao. "Kernel Meets Sieve: Transformed Hazards Models with Sparse Longitudinal Covariates." Journal of the American Statistical Association 120(552), 2580-2591. doi:10.1080/01621459.2025.2476781

Sun, Zhuowei, Hongyuan Cao, and Li Chen. "Regression Analysis of Additive Hazards Model with Sparse Longitudinal Covariates." Lifetime Data Analysis (2022). doi:10.1007/s10985-022-09548-6

Examples

library(survival)

set.seed(123)
dat <- sim_skmle_data(
  n = 80,
  mu = function(tt) 8 * (0.75 + (0.5 - tt)^2),
  mu_bar = 8,
  alpha = function(tt) 0.75 + 0.75 * (tt * (1 - sin(2 * pi * (tt - 0.25)))),
  beta = c(1, -0.5),
  s = 1,
  cen = 0.7
)

fit_add <- kee_additive(
  Surv(X, delta) ~ covariates,
  data = dat,
  id = id,
  obs_times = obs_times,
  h = 0.5
)

summary(fit_add)

Asynchronous longitudinal regression with time-invariant coefficients

Description

Regress a sparsely observed longitudinal response on a sparsely observed longitudinal covariate when the two are measured on different time grids and are never seen together.

Each response occasion TijT_{ij} is paired with every covariate occasion SikS_{ik} of the same subject, and each pair contributes in proportion to its time separation, so no pair is discarded and no value is carried forward. The estimator solves the kernel-weighted estimating equation of Cao, Zeng and Fine (2015),

Un(β)=n−1∑i∑j∑kWh(Tij−Sik)Xi(Sik)[Yi(Tij)−g{Xi(Sik)⊤β}]=0,U_n(\beta) = n^{-1} \sum_i \sum_j \sum_k W_h(T_{ij} - S_{ik}) X_i(S_{ik}) [ Y_i(T_{ij}) - g\{X_i(S_{ik})^\top \beta\} ] = 0,

with Wh(u)=W(u/h)/hW_h(u) = W(u/h)/h and WW the Epanechnikov kernel.

Usage

kee_async(
  data_y,
  data_x,
  formula,
  id,
  time,
  h = NULL,
  one_sided = FALSE,
  link = c("identity", "log", "logistic"),
  intercept = TRUE,
  maxit = 50L,
  tol = 1e-08
)

Arguments

data_y

Data frame of response occasions: one row per time the response was recorded. First argument, so the function pipes.

data_x

Data frame of covariate occasions: one row per time the covariates were recorded. Its time grid need not overlap data_y's at all.

formula

A two-sided formula, y ~ x1 + x2. The left-hand side is looked up in data_y and the right-hand side in data_x, which is the one unusual thing about this interface and follows from the data being in two tables: there is no single frame holding both.

id

Subject identifier naming a column present in both tables. Give it unquoted (id = subject), as a string (id = "subject"), or embraced (id = {{ col }}) when calling from inside another function. Non-numeric identifiers are allowed.

time

Observation time, naming a column present in both tables. Accepts the same three forms as id.

h

Positive bandwidth, on the same scale as time. If omitted, a value is read off the observation times as a rule of thumb and reported in a message.

one_sided

Logical. FALSE (default) is the full two-sided kernel of the paper; TRUE is the half kernel, admitting only covariate observations strictly before the response.

link

One of "identity" (closed form), "log" or "logistic" (Newton-Raphson).

intercept

Logical, include an intercept.

maxit, tol

Newton-Raphson controls, ignored when link = "identity".

Value

An object of class kee with components

coefficients

Named coefficient vector.

var

Sandwich covariance matrix A−1BA−1A^{-1} B A^{-1}.

A, Sigma

The bread and the meat of the sandwich.

scores

Per-subject score contributions, one row per subject; Sigma is crossprod(scores).

n

Number of subjects, the unit the asymptotics are in.

npair

Number of weighted (response, covariate) pairs contributing.

h, one_sided, link

Fit settings.

convergence

0 converged, 1 singular, 2 hit maxit.

call

The matched call.

coef(), vcov(), confint(), nobs(), print() and summary() methods are available.

Bandwidth

h is on the same scale as the observation times. Small h admits few pairs; large h admits pairs far apart in time. Fit at a few values of h and compare the estimates. A warning is issued when fewer than 5% of response occasions have any covariate observation in their window, which usually means h is on the wrong scale.

Half kernel or full kernel

one_sided = FALSE, the default, is the full two-sided kernel of the paper. one_sided = TRUE admits only covariate observations strictly before the response. It uses roughly half the pairs, so it needs a larger h for the same effective sample size.

Observation times are assumed independent of the response and covariate processes.

References

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.

See Also

kee_async_td() for a coefficient curve β(t)\beta(t), sim_async_data() to simulate.

Examples

set.seed(1)
d <- sim_async_data(n = 150, beta = c(0.5, 1.5))

# The two tables are on different time grids and share only `id`.
head(d$y, 3)
head(d$x, 3)

fit <- kee_async(d$y, d$x, y ~ x, id = id, time = time, h = 0.25)
summary(fit)
confint(fit)
tidy(fit, conf.int = TRUE)

# Data comes first, so it pipes.
d$y |>
  kee_async(d$x, y ~ x, id = id, time = time, h = 0.25) |>
  glance()

# Half kernel: only covariate observations preceding the response.
kee_async(d$y, d$x, y ~ x, id = id, time = time, h = 0.25, one_sided = TRUE)

Asynchronous longitudinal regression with time-dependent coefficients

Description

Fit E{Y(t)∣X(t)}=g{X(t)⊤β(t)}E\{Y(t) \mid X(t)\} = g\{X(t)^\top \beta(t)\} from asynchronous sparse longitudinal data, estimating the coefficient curve β(t)\beta(t) pointwise. This is the time-dependent coefficient estimator of Cao, Zeng and Fine (2015), the companion to kee_async().

At a target time tt a response occasion and a covariate occasion are weighted by their separate distances to tt,

Un{β(t)}=n−1∑i∑j∑kWh1(t−Tij)Wh2(t−Sik)Xi(Sik)[Yi(Tij)−g{Xi(Sik)⊤β(t)}]=0.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}) [ Y_i(T_{ij}) - g\{X_i(S_{ik})^\top \beta(t)\} ] = 0.

The lag between the two occasions never enters, only their distances to tt. That is the difference from kee_async(), where the lag is everything.

Usage

kee_async_td(
  data_y,
  data_x,
  formula,
  id,
  time,
  times = NULL,
  h = NULL,
  h2 = h,
  one_sided = FALSE,
  link = c("identity", "log", "logistic"),
  intercept = TRUE,
  maxit = 50L,
  tol = 1e-08
)

## S3 method for class 'kee_td'
print(x, ...)

Arguments

data_y

Data frame of response occasions: one row per time the response was recorded. First argument, so the function pipes.

data_x

Data frame of covariate occasions: one row per time the covariates were recorded. Its time grid need not overlap data_y's at all.

formula

A two-sided formula, y ~ x1 + x2. The left-hand side is looked up in data_y and the right-hand side in data_x, which is the one unusual thing about this interface and follows from the data being in two tables: there is no single frame holding both.

id

Subject identifier naming a column present in both tables. Give it unquoted (id = subject), as a string (id = "subject"), or embraced (id = {{ col }}) when calling from inside another function. Non-numeric identifiers are allowed.

time

Observation time, naming a column present in both tables. Accepts the same three forms as id.

times

Numeric vector of target times at which to estimate β(t)\beta(t). Defaults to 25 points spanning the 10th to 90th percentile of the observed response times, which keeps them inside the data: target times near the ends of the range are fitted from a one-sided window and are the least reliable part of the curve.

h

Bandwidth for the response side, h1h_1. If omitted, a rule-of-thumb value is used and reported in a message; see kee_async().

h2

Bandwidth for the covariate side, h2h_2. Defaults to h.

one_sided

Logical. FALSE (default) is the full two-sided kernel. TRUE restricts the covariate side to observations strictly before the target time, so β(t)\beta(t) uses only covariate values already available at t. The response side stays two-sided: it is a local average around t; restricting it as well would give a filtering estimate, which answers a different question. Both lags are measured as "how far in the past", matching kee_async() and the survival estimators.

link

One of "identity" (closed form), "log" or "logistic" (Newton-Raphson).

intercept

Logical, include an intercept.

maxit, tol

Newton-Raphson controls, ignored when link = "identity".

x

A kee_td object.

...

Ignored.

Value

An object of class kee_td:

coefficients

length(times) by p matrix of β^(t)\hat\beta(t).

se, z, p.value

Pointwise standard errors and Wald statistics, the same shape as coefficients.

var

List of p×pp \times p sandwich matrices, one per target time.

times, h, h2, one_sided, link, n

Fit settings.

nactive

Covariate rows carrying nonzero weight at each target time.

convergence

Per target time: 0 converged, 1 singular, 2 hit maxit, 3 no data in the window.

coef(), vcov(), confint(), nobs(), print() and plot() methods are available.

Reading the output

se holds sandwich standard errors at each target time; the bands drawn by plot.kee_td() are pointwise. Keep times inside the observed time range. Both time arguments are smoothed, so the curve needs more data than a time-invariant fit from kee_async().

Cost

The product weight factorises over the two occasion indices, so no pair is ever enumerated: the response side collapses to two per-subject scalars and the covariate side to one weight per row. Each target time costs O(ny+nxp2)O(n_y + n_x p^2). Fits at successive target times are warm-started from the previous solution when the link is nonlinear.

References

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.

See Also

kee_async(), plot.kee_td()

Examples

set.seed(1)
d <- sim_async_data(n = 200, beta = function(tt) cbind(0.5, 1 + tt))
fit <- d$y |>
  kee_async_td(d$x, y ~ x,
    id = id, time = time,
    times = seq(0.2, 0.8, by = 0.1), h = 0.3
  )
coef(fit)
tidy(fit)

Fit a Cox-Type KEE Model

Description

Fit the proportional hazards model for sparse longitudinal covariate data using a kernel estimating-equation approach.

Usage

kee_cox(
  formula,
  data,
  id,
  obs_times,
  h = NULL,
  one_sided = TRUE,
  weight = NULL
)

Arguments

formula

A model formula with a survival::Surv() response.

data

Data frame containing all variables used in the fit.

id

Subject identifier aligned row-wise with data.

obs_times

Longitudinal observation times aligned row-wise with data. Times may be on any scale, so there is no need to rescale to the unit interval first. h must be on the same scale. Observation times may be negative; see “Negative observation times” in kee_cox().

h

Positive kernel bandwidth. If omitted, one is read off the observation times as a rule of thumb and reported in a message. Use skmle_cv() to choose it from the data.

one_sided

Logical. TRUE (the default) uses a half kernel: only covariate observations strictly before the event or quadrature time inform that time, which is the risk-set restriction and the estimator as published. FALSE uses a full, two-sided kernel, smoothing the covariate path from both sides. The switch applies to the risk-set averages inside the C++ backend as well as to the row weights, so the two are always consistent.

weight

Weight function of the standardised lag (t−r)/h(t - r)/h, or NULL (the default) for the Epanechnikov kernel implied by one_sided. Any R function will do; see kernel-weights.

Details

kee_cox() targets the proportional hazards case without estimating a nonparametric baseline component. It is therefore a useful specialized alternative to skmle() when the scientific model is Cox-type and the main interest is in the regression coefficients.

Value

An object of class kee containing coefficient estimates, the estimated variance-covariance matrix, the estimating-equation matrices W and Sigma, the per-subject score contributions scores (one row per subject, so that Sigma is crossprod(scores) / n^2), convergence status, and the original function call.

Negative observation times

obs_times may be negative. Event times may not, and a negative event time is an error: in skmle() and kee_additive() the sieve basis and the cumulative-hazard quadrature are built on ⁠[0, max(X)]⁠, and every estimator takes the time origin to be zero. Observation times carry no such constraint. They enter the score only through the lag X - obs_times, and the half kernel admits a row on the sign of that lag rather than on the sign of the time, so a covariate observed at -180 and an event at 30 sit a lag of 210 apart and are handled like any other pair.

A pre-origin observation contributes only where it falls within h of an event time. Use negative times for ordinary measurements taken before entry on the same scale, such as a run-in visit or a screening draw.

References

Sun, Dayu, Zhuowei Sun, Xingqiu Zhao, and Hongyuan Cao. "Kernel Meets Sieve: Transformed Hazards Models with Sparse Longitudinal Covariates." Journal of the American Statistical Association 120(552), 2580-2591. doi:10.1080/01621459.2025.2476781

Cao, Hongyuan, Mathew M. Churpek, Donglin Zeng, and Jason P. Fine. "Analysis of the Proportional Hazards Model with Sparse Longitudinal Covariates." Journal of the American Statistical Association 110(511), 1187-1196 (2015). doi:10.1080/01621459.2014.957289

Examples

library(survival)

set.seed(123)
dat <- sim_skmle_data(
  n = 80,
  mu = function(tt) 8 * (0.75 + (0.5 - tt)^2),
  mu_bar = 8,
  alpha = function(tt) 0.5 * 0.75 + 0.75 * (tt * (1 - sin(2 * pi * (tt - 0.25)))),
  beta = c(1, -0.5),
  s = 0,
  cen = 0.7
)

fit_cox <- kee_cox(
  Surv(X, delta) ~ covariates,
  data = dat,
  id = id,
  obs_times = obs_times,
  h = 0.5
)

summary(fit_cox)

Kernel weight functions

Description

A weight function says how much a covariate observation at lag u from a time contributes to the estimating equation at that time, where u is the lag divided by the bandwidth. Every estimator in this package takes one through its weight argument, and any R function of u will do: the Epanechnikov kernels here are a starting point, not the only option.

Usage

w_epan_half()

w_epan_full()

Value

A function of one argument, the standardised lag u=(t−r)/hu = (t - r)/h as a vector or a matrix, returning the weight with the shape of its argument preserved and carrying a support attribute.

Functions

  • w_epan_half(): The Epanechnikov half kernel 0.75(1−u2)+0.75(1 - u^2)_+ on [0,1][0, 1], the default for the survival estimators and the weight every published result in this package was computed with.

  • w_epan_full(): The Epanechnikov full kernel 0.75(1−u2)+0.75(1 - u^2)_+ on [−1,1][-1, 1], the default for the asynchronous longitudinal estimators and the kernel of Cao, Zeng and Fine (2015). Symmetry kills the first moment, so it is order 2.

Writing your own

A weight is a function of one argument, the standardised lag u=(t−r)/hu = (t - r)/h, returning a value of the same shape. It is called on vectors and on matrices, and it must preserve the shape it is given: the sieve quadrature evaluates it on a matrix of node-by-observation lags. Zero outside its own support is the function's own responsibility.

gauss_half <- function(u) exp(-u^2 / 2) * (u >= 0 & u <= 3)
kee_cox(Surv(X, delta) ~ z, data, id = id, obs_times = r,
        h = 0.3, weight = gauss_half)

Nothing about the function has to be polynomial, nonnegative or symmetric. A weight that takes negative values is supported throughout: the estimating equations admit a row on whether its weight is nonzero, not on whether it is positive.

support is the one attribute worth setting, as a length-2 numeric giving the interval outside which the weight is zero. It is used to enumerate pairs in the asynchronous estimators, where scanning every pair would otherwise be quadratic, and to choose the rows that carry a feasibility constraint in skmle() with s != 0. Without it a default of ⁠[-1, 1]⁠ is assumed; the constraint rows also include every row whose weight is nonzero, so a missing attribute never leaves a weighted row unconstrained.

The same weight is used in every term of each estimating equation: the row weights, the risk-set averages and, for skmle(), the cumulative-hazard integral and both sandwich matrices. Nothing in the package falls back to a built-in kernel.

Scaling

The weight is used as W(u)/hW(u)/h. A weight that integrates to something other than 1 is not wrong: the normalisation cancels wherever the weight appears in a ratio, which is everywhere in the risk-set averages, and is absorbed into h elsewhere. w_epan_half() integrates to 1/2 for that reason and is the weight every published result in this package used.

The one-sided restriction is separate

one_sided is a modelling choice, not a property of the weight. It is the risk-set restriction of a hazard model: only covariate observations strictly before a time may inform it. It is applied on the sign of the lag after the weight has been evaluated, so a two-sided weight under one_sided = TRUE is truncated at zero rather than rejected.

Examples

W <- w_epan_half()
W(c(-0.5, 0, 0.5, 1, 1.5))
attr(W, "support")

# Any function of the standardised lag is a weight.
tri <- function(u) pmax(1 - abs(u), 0)
tri(c(-0.5, 0, 0.5))

Number of subjects contributing to a fit

Description

Returns the number of subjects, which is what summary() prints as n.

Usage

## S3 method for class 'skmle'
nobs(object, ...)

## S3 method for class 'kee'
nobs(object, ...)

## S3 method for class 'kee_td'
nobs(object, ...)

Arguments

object

A fitted skmle, kee or kee_td object.

...

Unused.

Value

An integer, the number of subjects.

Examples

set.seed(1)
d <- sim_async_data(n = 120)
fit <- kee_async(d$y, d$x, y ~ x, id = id, time = time, h = 0.3)
nobs(fit)

Plot a cross-validation curve

Description

The held-out loss against the candidate bandwidths, with the selected value marked. Worth a glance every time: if the curve is still falling at an endpoint of the grid, the "selected" bandwidth is where you stopped looking rather than a minimum, and the grid should be widened.

Usage

## S3 method for class 'cv.skmle'
plot(x, ...)

Arguments

x

A cv.skmle object.

...

Passed to graphics::plot().

Value

x, invisibly. Called for the plot.

Examples

library(survival)
set.seed(123)
dat <- sim_skmle_data(
  n = 60,
  mu = function(tt) 8 * (0.75 + (0.5 - tt)^2),
  mu_bar = 8,
  alpha = function(tt) 0.5 * 0.75 + 0.75 * (tt * (1 - sin(2 * pi * (tt - 0.25)))),
  beta = c(1, -0.5),
  s = 0,
  cen = 0.7
)
cv <- skmle_cv(Surv(X, delta) ~ covariates, data = dat, id = id,
  obs_times = obs_times, s = 0, K = 3, seed = 2026, quiet = TRUE)
plot(cv)

Plot estimated coefficient curves

Description

Draws β^j(t)\hat\beta_j(t) against t with pointwise Wald bands, one panel per coefficient.

Usage

## S3 method for class 'kee_td'
plot(x, which = seq_len(ncol(x$coefficients)), level = 0.95, ...)

Arguments

x

A kee_td object from kee_async_td().

which

Integer or character vector selecting coefficients to draw. Defaults to all.

level

Confidence level for the pointwise bands.

...

Passed to graphics::plot().

Value

x, invisibly. Called for the plot.

Examples

set.seed(1)
d <- sim_async_data(n = 200, beta = function(tt) cbind(0.5, 1 + tt))
fit <- d$y |>
  kee_async_td(d$x, y ~ x,
    id = id, time = time,
    times = seq(0.2, 0.8, by = 0.05), h = 0.3
  )
plot(fit)

Plot the estimated baseline function for skmle model

Description

Plot the estimated baseline function for skmle model

Usage

## S3 method for class 'skmle'
plot(x, t_seq = NULL, ...)

Arguments

x

An object of class skmle.

t_seq

Time points at which to evaluate the baseline. Defaults to 100 points spanning the follow-up the model was fitted on.

...

Further arguments passed to or from other methods.

Value

A ggplot object showing the estimated nonparametric baseline function evaluated on t_seq.

Examples

library(survival)

set.seed(123)
dat <- sim_skmle_data(
  n = 60,
  mu = function(tt) 8 * (0.75 + (0.5 - tt)^2),
  mu_bar = 8,
  alpha = function(tt) 0.5 * 0.75 + 0.75 * (tt * (1 - sin(2 * pi * (tt - 0.25)))),
  beta = c(1, -0.5),
  s = 0,
  cen = 0.7
)

fit <- skmle(Surv(X, delta) ~ covariates, data = dat, id = id,
             obs_times = obs_times, s = 0, h = 0.5, nknots = 3)
plot(fit)

Print kee object

Description

Print kee object

Usage

## S3 method for class 'kee'
print(x, ...)

Arguments

x

An object of class kee.

...

Further arguments passed to or from other methods.

Value

x, invisibly. Called for its side effect of printing a brief summary of the call and estimated coefficients.

Examples

library(survival)

set.seed(123)
dat <- sim_skmle_data(
  n = 60,
  mu = function(tt) 8 * (0.75 + (0.5 - tt)^2),
  mu_bar = 8,
  alpha = function(tt) 0.5 * 0.75 + 0.75 * (tt * (1 - sin(2 * pi * (tt - 0.25)))),
  beta = c(1, -0.5),
  s = 0,
  cen = 0.7
)

fit <- kee_cox(Surv(X, delta) ~ covariates, data = dat, id = id,
               obs_times = obs_times, h = 0.5)
print(fit)

Print skmle object

Description

Print skmle object

Usage

## S3 method for class 'skmle'
print(x, ...)

Arguments

x

An object of class skmle.

...

Further arguments passed to or from other methods.

Value

x, invisibly. Called for its side effect of printing a brief summary of the call and estimated coefficients.

Examples

library(survival)

set.seed(123)
dat <- sim_skmle_data(
  n = 60,
  mu = function(tt) 8 * (0.75 + (0.5 - tt)^2),
  mu_bar = 8,
  alpha = function(tt) 0.5 * 0.75 + 0.75 * (tt * (1 - sin(2 * pi * (tt - 0.25)))),
  beta = c(1, -0.5),
  s = 0,
  cen = 0.7
)

fit <- skmle(Surv(X, delta) ~ covariates, data = dat, id = id,
             obs_times = obs_times, s = 0, h = 0.5, nknots = 3)
print(fit)

Print summary of kee object

Description

Print summary of kee object

Usage

## S3 method for class 'summary.kee'
print(x, ...)

Arguments

x

An object of class summary.kee.

...

Further arguments passed to or from other methods.

Value

x, invisibly. Called for its side effect of printing the summary table.

Examples

library(survival)

set.seed(123)
dat <- sim_skmle_data(
  n = 60,
  mu = function(tt) 8 * (0.75 + (0.5 - tt)^2),
  mu_bar = 8,
  alpha = function(tt) 0.5 * 0.75 + 0.75 * (tt * (1 - sin(2 * pi * (tt - 0.25)))),
  beta = c(1, -0.5),
  s = 0,
  cen = 0.7
)

fit <- kee_cox(Surv(X, delta) ~ covariates, data = dat, id = id,
               obs_times = obs_times, h = 0.5)
print(summary(fit))

Print summary of skmle object

Description

Print summary of skmle object

Usage

## S3 method for class 'summary.skmle'
print(x, ...)

Arguments

x

An object of class summary.skmle.

...

Further arguments passed to or from other methods.

Value

x, invisibly. Called for its side effect of printing the summary table.

Examples

library(survival)

set.seed(123)
dat <- sim_skmle_data(
  n = 60,
  mu = function(tt) 8 * (0.75 + (0.5 - tt)^2),
  mu_bar = 8,
  alpha = function(tt) 0.5 * 0.75 + 0.75 * (tt * (1 - sin(2 * pi * (tt - 0.25)))),
  beta = c(1, -0.5),
  s = 0,
  cen = 0.7
)

fit <- skmle(Surv(X, delta) ~ covariates, data = dat, id = id,
             obs_times = obs_times, s = 0, h = 0.5, nknots = 3)
print(summary(fit))

Simulate asynchronous longitudinal data

Description

Draw a sparse longitudinal response and a sparse longitudinal covariate whose observation times are independent, so the two are never seen together. This is the design of Cao, Zeng and Fine (2015), Section 4: response times and covariate times are independent Poisson streams on (0,1)(0, 1), the covariate is a mean-zero Gaussian process, and the error is a second, independent Gaussian process.

Usage

sim_async_data(
  n,
  beta = c(0.5, 1.5),
  lambda_y = 5,
  lambda_x = 5,
  link = c("identity", "log", "logistic"),
  x_cov = function(s, t) exp(-abs(s - t)),
  e_cov = function(s, t) 2^(-abs(s - t))
)

Arguments

n

Number of subjects.

beta

Either a numeric vector c(intercept, slopes) or a function of a numeric time vector returning a matrix with length(beta(t)) columns and one row per time.

lambda_y, lambda_x

Poisson rates for the response and covariate observation streams on ⁠(0, 1)⁠. Each subject is forced to have at least one observation of each.

link

One of "identity", "log" or "logistic", matching kee_async(). Under "logistic" the response is Bernoulli and no error process is added; under "log" the response is Poisson.

x_cov, e_cov

Covariance functions of two times, vectorised, for the covariate and error processes.

Details

The default covariate covariance exp⁡(−∣s−t∣)\exp(-|s - t|) is the Ornstein- Uhlenbeck covariance. Its diagonal has a kink, so it is only one-sided differentiable, which is exactly the case Cao, Zeng and Fine's Section 6 leaves open. Supply a smooth x_cov, for instance function(s, t) exp(-(s - t)^2), to generate data inside their stated assumptions instead.

beta may be a numeric vector, giving time-invariant coefficients suitable for kee_async(), or a function of time returning one row per supplied time, giving a coefficient curve suitable for kee_async_td(). In both cases the first element is the intercept and the remaining p elements multiply the p covariate coordinates.

Value

A list of two tibbles on different time grids:

y

id, time, y – one row per response occasion.

x

id, time, and one column per covariate coordinate – named x when there is a single covariate, x1, x2, ... otherwise. One row per covariate occasion, on a time grid independent of y's.

References

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.

Examples

set.seed(1)
d <- sim_async_data(n = 50)
str(d)

# The two tables share `id` and nothing else; their `time` grids are
# independent draws, which is what makes the data asynchronous.
head(d$y, 3)
head(d$x, 3)

# A coefficient curve, for kee_async_td().
d2 <- sim_async_data(n = 50, beta = function(tt) cbind(0.5, 1 + tt))

Simulate Sparse Longitudinal Survival Data

Description

Simulate right-censored survival data with sparsely and intermittently observed longitudinal covariates under a transformed hazards model.

Usage

sim_skmle_data(n, mu, mu_bar, alpha, beta, s, cen, nstep = 20)

Arguments

n

Number of subjects to simulate.

mu

Function giving the intensity of the observation-time process for the longitudinal covariates.

mu_bar

Numeric upper bound for mu on the follow-up interval.

alpha

Function giving the baseline component of the transformed hazards model.

beta

Numeric vector of true regression coefficients. The current simulator supports exactly two covariates, so length(beta) must equal 2.

s

Box-Cox transformation parameter. Use s = 0 for a proportional hazards model and s = 1 for an additive hazards model.

cen

Positive censoring parameter controlling the follow-up window.

nstep

Number of grid intervals used to generate the latent piecewise-constant time-varying covariate process.

Details

The simulated data are returned in long format, with one row per subject-visit pair. Each row contains the observed event or censoring time, the event indicator, the observation time for the longitudinal covariate, and the covariate values observed at that visit.

The first covariate is generated as a latent step function over time. The second covariate is a binary subject-level indicator. Event times are generated by numerically inverting the cumulative transformed hazard, and observation times are generated from a non-homogeneous Poisson process.

Value

A tibble in long format with columns:

  • id: subject identifier.

  • X: observed event or censoring time.

  • delta: event indicator.

  • covariates: a two-column matrix of observed covariates at obs_times.

  • obs_times: longitudinal observation time.

  • censoring: subject-specific censoring time.

Examples

set.seed(123)
sim_data <- sim_skmle_data(
  n = 50,
  mu = function(tt) 8 * (0.75 + (0.5 - tt)^2),
  mu_bar = 8,
  alpha = function(tt) 0.5 * 0.75 + 0.75 * (tt * (1 - sin(2 * pi * (tt - 0.25)))),
  beta = c(1, -0.5),
  s = 0,
  cen = 0.7
)

head(sim_data)
table(sim_data$delta)

# The `covariates` column is a matrix; use it directly in model formulas
# or split it into explicit columns if preferred.
sim_data$Z1 <- sim_data$covariates[, 1]
sim_data$Z2 <- sim_data$covariates[, 2]
head(sim_data[, c("id", "X", "delta", "obs_times", "Z1", "Z2")])

Fit a Transformed Hazards Model by SMKLE

Description

Fit a transformed hazards model for survival data with sparsely and intermittently observed longitudinal covariates using the sieve maximum kernel-weighted log-likelihood estimator (SMKLE).

Usage

skmle(
  formula,
  data,
  id,
  obs_times,
  s = 0,
  h = NULL,
  nknots = 3,
  lq_nodes = 64,
  maxeval = 10000,
  xtol_rel = 1e-06,
  one_sided = TRUE,
  weight = NULL,
  optimizer = c("slsqp", "barrier")
)

Arguments

formula

A model formula. The left-hand side must be a survival::Surv() response and the right-hand side must contain at least one covariate.

data

Data frame containing the variables used in formula, id, and obs_times.

id

Subject identifier. Non-numeric identifiers are allowed and are internally converted to integer subject codes.

obs_times

Longitudinal observation times aligned row-wise with data. Times may be on any scale; the sieve basis and the cumulative-hazard quadrature are built on the observed follow-up, so there is no need to rescale to the unit interval first. h must be on the same scale.

s

Box-Cox transformation parameter, defaulting to 0. s = 0 is the proportional hazards model, s = 1 is the additive hazards model, and values in between interpolate. If you do not have a reason to choose otherwise, the default is the familiar Cox model.

h

Positive kernel bandwidth. If omitted, one is read off the observation times as a rule of thumb and reported in a message. Use skmle_cv() to choose it from the data.

nknots

Number of interior knots used in the sieve approximation of the baseline component. Knots are placed at tau * (1:nknots)/(nknots + 1), where tau is the largest observed event or censoring time. The basis is a natural cubic spline (splines::ns); its order is fixed, which is why there is no norder argument.

lq_nodes

Number of Legendre-Gauss quadrature nodes used in numerical integration.

maxeval

Maximum number of optimizer evaluations.

xtol_rel

Relative convergence tolerance passed to the optimizer.

one_sided

Logical. TRUE (the default) uses a half kernel: only covariate observations strictly before the event or quadrature time inform that time, which is the risk-set restriction and the estimator as published. FALSE uses a full, two-sided kernel, smoothing the covariate path from both sides. The switch applies to the risk-set averages inside the C++ backend as well as to the row weights, so the two are always consistent.

weight

Weight function of the standardised lag (t−r)/h(t - r)/h, or NULL (the default) for the Epanechnikov kernel implied by one_sided. Any R function will do; see kernel-weights.

optimizer

"slsqp" (the default) maximises the objective with NLopt's SLSQP, constraining 1 + s * eta >= 0 at the event-time rows and flooring the hazard elsewhere, which is the estimator as published. "barrier" uses an interior-point (log-barrier) Newton method that keeps 1 + s * eta > 0 at every point the objective evaluates, event rows and quadrature pairs alike, so no floor is needed. For ⁠0 <= s <= 1⁠ that problem is concave and the barrier fit is its global optimum. The two coincide at s = 0, where there are no constraints. maxeval and xtol_rel apply to "slsqp" only.

Details

skmle() is the main model-fitting function in the package. It combines:

  • kernel weighting to handle intermittently observed longitudinal covariates,

  • a sieve approximation for the unknown baseline component, and

  • a C++-backed numerical optimizer for the joint estimation problem.

The returned object follows the usual R model pattern: print the fitted coefficients with print(), obtain inferential output with summary(), and visualize the estimated baseline component with plot().

Value

An object of class skmle containing:

  • coefficients: regression coefficient estimates,

  • var: estimated variance-covariance matrix for the regression coefficients,

  • gamma: estimated spline coefficients for the baseline component,

  • loglik: maximized log-likelihood,

  • convergence: optimizer status code,

  • scores: per-subject contributions to the score for the coefficients (one row per subject), from which the sandwich's B is formed,

  • model metadata such as n, s, h, and call.

References

Sun, Dayu, Zhuowei Sun, Xingqiu Zhao, and Hongyuan Cao. "Kernel Meets Sieve: Transformed Hazards Models with Sparse Longitudinal Covariates." Journal of the American Statistical Association 120(552), 2580-2591. doi:10.1080/01621459.2025.2476781

Examples

library(survival)

set.seed(123)
dat <- sim_skmle_data(
  n = 80,
  mu = function(tt) 8 * (0.75 + (0.5 - tt)^2),
  mu_bar = 8,
  alpha = function(tt) 0.5 * 0.75 + 0.75 * (tt * (1 - sin(2 * pi * (tt - 0.25)))),
  beta = c(1, -0.5),
  s = 0,
  cen = 0.7
)

fit <- skmle(
  Surv(X, delta) ~ covariates,
  data = dat,
  id = id,
  obs_times = obs_times,
  s = 0,
  h = 0.5,
  nknots = 3
)

summary(fit)

Select the Bandwidth by Cross-Validation

Description

Perform K-fold cross-validation to select the kernel bandwidth for skmle().

Usage

skmle_cv(
  formula,
  data,
  id,
  obs_times,
  s = 0,
  K = 5,
  h_grid = NULL,
  n_h = 10,
  nknots = 3,
  lq_nodes = 64,
  maxeval = 10000,
  xtol_rel = 1e-06,
  seed = NULL,
  quiet = FALSE,
  one_sided = TRUE,
  weight = NULL
)

## S3 method for class 'cv.skmle'
print(x, ...)

Arguments

formula

A model formula. The left-hand side must be a survival::Surv() response and the right-hand side must contain at least one covariate.

data

Data frame containing the variables used in formula, id, and obs_times.

id

Subject identifier. Non-numeric identifiers are allowed and are internally converted to integer subject codes.

obs_times

Longitudinal observation times aligned row-wise with data. Times may be on any scale; the sieve basis and the cumulative-hazard quadrature are built on the observed follow-up, so there is no need to rescale to the unit interval first. h must be on the same scale.

s

Box-Cox transformation parameter, defaulting to 0. s = 0 is the proportional hazards model, s = 1 is the additive hazards model, and values in between interpolate. If you do not have a reason to choose otherwise, the default is the familiar Cox model.

K

Number of folds.

h_grid

Optional numeric vector of candidate bandwidth values. If NULL, a grid is generated automatically from the observed time gaps.

n_h

Number of candidate bandwidths to generate when h_grid is NULL.

nknots

Number of interior knots used in the sieve approximation of the baseline component. Knots are placed at tau * (1:nknots)/(nknots + 1), where tau is the largest observed event or censoring time. The basis is a natural cubic spline (splines::ns); its order is fixed, which is why there is no norder argument.

lq_nodes

Number of Legendre-Gauss quadrature nodes used in numerical integration.

maxeval

Maximum number of optimizer evaluations.

xtol_rel

Relative convergence tolerance passed to the optimizer.

seed

Optional integer seed for the random subject-to-fold assignment. If NULL, the current RNG state is used and no explicit seed is set. A supplied seed is used locally: the global RNG state is restored on exit.

quiet

Logical; if TRUE, suppress progress output.

one_sided

Logical. TRUE (the default) uses a half kernel: only covariate observations strictly before the event or quadrature time inform that time, which is the risk-set restriction and the estimator as published. FALSE uses a full, two-sided kernel, smoothing the covariate path from both sides. The switch applies to the risk-set averages inside the C++ backend as well as to the row weights, so the two are always consistent.

weight

Weight function of the standardised lag (t−r)/h(t - r)/h, or NULL (the default) for the Epanechnikov kernel implied by one_sided. Any R function will do; see kernel-weights.

x

A cv.skmle object.

...

Ignored.

Value

An object of class cv.skmle with components:

  • h_cv: selected bandwidth,

  • fit: skmle fit refit on the full data,

  • cv_results: data frame of candidate bandwidths, their CV losses, and the standard error of each loss across the folds,

  • h_grid: bandwidth grid used in the search,

  • fold_id: the subject-to-fold assignment vector (length n),

  • seed: the value of seed supplied by the user, or NULL,

  • call: the matched call.

Kernel choice

one_sided is used inside the fold loop as well as being passed through to the refit, so the bandwidth is selected under the same kernel the final fit uses.

How the folds are formed

skmle_cv() splits subjects across folds. Several rows belong to the same subject in long format, so splitting by row would put one subject on both sides of the split.

After choosing the bandwidth with the smallest average validation loss, the function refits skmle() on the full data set using the selected value. Because the fold assignment is random, pass seed (or set.seed() before calling) to make the grid selection reproducible.

The loss

Each training fold is fitted at the candidate bandwidth, and the fit is scored on the held-out subjects by the log-likelihood per subject,

−1ntest∑i∈test[δilog⁡g{α^(Xi)+Zi(Xi)⊤β^}−∫0Xig{α^(t)+Zi(t)⊤β^} dt],-\frac{1}{n_{\mathrm{test}}} \sum_{i \in \mathrm{test}} \left[ \delta_i \log g\{\hat\alpha(X_i) + Z_i(X_i)^\top \hat\beta\} - \int_0^{X_i} g\{\hat\alpha(t) + Z_i(t)^\top \hat\beta\}\,dt \right],

where Zi(t)Z_i(t) is the covariate carried forward from the last observation at or before tt. This loss does not depend on the bandwidth itself, so it compares candidates on an equal footing.

The grid

When h_grid is NULL the grid is log-spaced over [max⁡{min⁡i(Xi−Tij)+, τn−0.6}, min⁡{max⁡imax⁡j(Xi−Tij)+, τn−0.3}][\max\{\min_i (X_i - T_{ij})_+,\ \tau n^{-0.6}\},\ \min\{\max_i \max_j (X_i - T_{ij})_+,\ \tau n^{-0.3}\}], with τ=max⁡iXi\tau = \max_i X_i, so it adapts to the scale of the times on its own. If the selected value is an endpoint of the grid, skmle_cv() warns; supply a wider h_grid.

cv_results lists the loss and its standard error across folds for every candidate.

Examples

library(survival)

set.seed(123)
dat <- sim_skmle_data(
  n = 60,
  mu = function(tt) 8 * (0.75 + (0.5 - tt)^2),
  mu_bar = 8,
  alpha = function(tt) 0.5 * 0.75 + 0.75 * (tt * (1 - sin(2 * pi * (tt - 0.25)))),
  beta = c(1, -0.5),
  s = 0,
  cen = 0.7
)

cv_fit <- skmle_cv(
  Surv(X, delta) ~ covariates,
  data = dat,
  id = id,
  obs_times = obs_times,
  s = 0,
  K = 3,
  seed = 2026,
  quiet = TRUE
)

cv_fit$h_cv
# Read the whole table, not just the selection: a minimum on the edge of the
# grid is a boundary artefact and warns.
cv_fit$cv_results
summary(cv_fit$fit)

Summary for kee object

Description

Summary for kee object

Usage

## S3 method for class 'kee'
summary(object, ...)

Arguments

object

An object of class kee.

...

Further arguments passed to or from other methods.

Value

An object of class summary.kee containing the call, a coefficient table with estimates, standard errors, z-statistics and p-values, the convergence code, and the sample size n.

Examples

library(survival)

set.seed(123)
dat <- sim_skmle_data(
  n = 60,
  mu = function(tt) 8 * (0.75 + (0.5 - tt)^2),
  mu_bar = 8,
  alpha = function(tt) 0.5 * 0.75 + 0.75 * (tt * (1 - sin(2 * pi * (tt - 0.25)))),
  beta = c(1, -0.5),
  s = 0,
  cen = 0.7
)

fit <- kee_cox(Surv(X, delta) ~ covariates, data = dat, id = id,
               obs_times = obs_times, h = 0.5)
summary(fit)

Summary for skmle object

Description

Summary for skmle object

Usage

## S3 method for class 'skmle'
summary(object, ...)

Arguments

object

An object of class skmle.

...

Further arguments passed to or from other methods.

Value

An object of class summary.skmle containing the call, a coefficient table with estimates, standard errors, z-statistics and p-values, the log-likelihood, convergence status, and the sample size n.

Examples

library(survival)

set.seed(123)
dat <- sim_skmle_data(
  n = 60,
  mu = function(tt) 8 * (0.75 + (0.5 - tt)^2),
  mu_bar = 8,
  alpha = function(tt) 0.5 * 0.75 + 0.75 * (tt * (1 - sin(2 * pi * (tt - 0.25)))),
  beta = c(1, -0.5),
  s = 0,
  cen = 0.7
)

fit <- skmle(Surv(X, delta) ~ covariates, data = dat, id = id,
             obs_times = obs_times, s = 0, h = 0.5, nknots = 3)
summary(fit)

Summarise a fit as a tibble

Description

One row per coefficient for skmle and kee fits, and one row per (target time, coefficient) for kee_td, so a coefficient curve goes straight into ggplot2 without reshaping.

Usage

## S3 method for class 'skmle'
tidy(x, conf.int = FALSE, conf.level = 0.95, ...)

## S3 method for class 'kee'
tidy(x, conf.int = FALSE, conf.level = 0.95, ...)

## S3 method for class 'kee_td'
tidy(x, conf.int = FALSE, conf.level = 0.95, ...)

Arguments

x

A fitted skmle, kee or kee_td object.

conf.int

Logical, add conf.low and conf.high columns.

conf.level

Confidence level for those columns.

...

Unused.

Value

A tibble with columns term, estimate, std.error, statistic and p.value, preceded by time for a kee_td fit, and followed by conf.low and conf.high when conf.int = TRUE.

Examples

set.seed(1)
d <- sim_async_data(n = 150)
fit <- kee_async(d$y, d$x, y ~ x, id = id, time = time, h = 0.3)
tidy(fit, conf.int = TRUE)

Extract the covariance matrix of a fitted model

Description

Extract the covariance matrix of a fitted model

Usage

## S3 method for class 'skmle'
vcov(object, ...)

## S3 method for class 'kee'
vcov(object, ...)

## S3 method for class 'kee_td'
vcov(object, time = NULL, ...)

Arguments

object

A fitted skmle, kee or kee_td object.

...

Unused.

time

For a kee_td fit, the target time whose covariance matrix is wanted. Matched to the nearest fitted target time. When NULL the full list of matrices is returned, one per target time.

Value

For skmle and kee, the estimated covariance matrix of the regression coefficients. For kee_td, see time.

Examples

set.seed(1)
d <- sim_async_data(n = 120)
fit <- kee_async(d$y, d$x, y ~ x, id = id, time = time, h = 0.3)
vcov(fit)