--- title: "Getting Started with skmle" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Getting Started with skmle} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 7, fig.height = 4 ) ``` ## Overview A longitudinal covariate is rarely measured at the time you need it. `skmle` handles that mismatch by weighting each observation according to how far its measurement time sits from the time being modelled, rather than carrying a value forward or smoothing the covariate and substituting it. Two outcome types are covered. **Survival outcomes**, where the covariate is observed sparsely and intermittently over follow-up: 1. `skmle()` for the general transformed hazards model. 2. `kee_cox()` for the proportional hazards estimating-equation approach. 3. `kee_additive()` for the additive hazards estimating-equation approach. **Asynchronous longitudinal outcomes**, where the outcome is itself a sparsely observed process recorded on a time grid that does not line up with the covariate's: 4. `kee_async()` for time-invariant coefficients. 5. `kee_async_td()` for a coefficient curve $\beta(t)$. This vignette walks through both: simulate data, fit a model, inspect the summary output, plot the estimated baseline component, select a bandwidth by cross-validation, then move to the asynchronous longitudinal setting. ## Which function do I need? Two questions. First, what is the outcome? A *time to an event* (death, relapse, failure), possibly censored? Use the survival estimators; your data is one long table. Or a *repeatedly measured quantity* (a score, a lab value) recorded on its own schedule? Use the asynchronous estimators; your data is two tables. Then: | Outcome | Situation | Function | | :-- | :-- | :-- | | Survival | Start here; Cox model | `kee_cox()` | | Survival | Additive hazards instead | `kee_additive()` | | Survival | Want the baseline hazard, or a model between the two | `skmle()` | | Survival | Choose the bandwidth | `skmle_cv()` | | Longitudinal | Start here; one constant effect | `kee_async()` | | Longitudinal | The effect may change over time | `kee_async_td()` | Every fitting function picks a bandwidth for you if you do not supply one, and says in a message what it chose. For the survival models, `skmle_cv()` chooses it from the data. ```{r setup, warning=FALSE, message=FALSE} library(skmle) library(survival) ``` ## Simulating some data ```{r} 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 ) head(dat) ``` The simulated data are stored in long format. Each row corresponds to one observed longitudinal measurement time for one subject. The key columns are: - `id`: subject identifier - `X`: observed event or censoring time - `delta`: event indicator - `covariates`: observed covariate values at that visit time - `obs_times`: longitudinal observation time ## Fitting the general transformed hazards model The `covariates` column returned by `sim_skmle_data()` is a matrix. You can either use it directly in the formula or split it into separate columns. Using the matrix directly is convenient for routine work. ```{r} fit_skmle <- skmle( Surv(X, delta) ~ covariates, data = dat, id = id, obs_times = obs_times, s = 0, h = 0.5, nknots = 3 ) fit_skmle ``` The printed object gives the fitted coefficients. As in many R model objects, the formatted inferential output is produced by `summary()`. ```{r} summary(fit_skmle) ``` The summary table reports: - coefficient estimates - standard errors - z statistics - p-values ## Plotting the baseline ```{r} plot(fit_skmle) ``` This plot visualizes the estimated nonparametric baseline component from the sieve fit. ## The specialised estimating equations When the model of interest matches one of the specialized settings, the package also provides dedicated estimating-equation estimators. ### Cox-type ```{r} fit_kee_cox <- kee_cox( Surv(X, delta) ~ covariates, data = dat, id = id, obs_times = obs_times, h = 0.5 ) summary(fit_kee_cox) ``` ### Additive hazards For the additive hazards estimator, simulate data under `s = 1`. ```{r} set.seed(456) dat_add <- 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_kee_add <- kee_additive( Surv(X, delta) ~ covariates, data = dat_add, id = id, obs_times = obs_times, h = 0.5 ) summary(fit_kee_add) ``` ## Selecting a bandwidth Bandwidth selection can be handled by `skmle_cv()`. Leave `h_grid` out and it builds one from the observation times, log-spaced over the range the theory supports. ```{r} set.seed(999) cv_fit <- skmle_cv( Surv(X, delta) ~ covariates, data = dat, id = id, obs_times = obs_times, s = 0, K = 3, nknots = 3, quiet = TRUE ) cv_fit$h_cv cv_fit$cv_results ``` The returned object contains: - the selected bandwidth - the refitted `skmle` model at that bandwidth - the cross-validation loss table `cv_results` holds the held-out loss and its standard error for each candidate bandwidth. If the selected value sits at an end of the grid, `skmle_cv()` warns; pass a wider `h_grid`. You can then inspect the final refit in the usual way. ```{r} summary(cv_fit$fit) ``` ## Half kernel or full kernel Every estimator weights a covariate observation by how far it sits from the time being modelled. For the survival estimators that window is *one-sided* by default: only observations strictly before the time contribute, which is the risk-set restriction of a hazard model. Set `one_sided = FALSE` to smooth the covariate path from both sides instead. ```{r one-sided} fit_full <- kee_cox( Surv(X, delta) ~ covariates, data = dat, id = id, obs_times = obs_times, h = 0.5, one_sided = FALSE ) cbind(half = coef(fit_kee_cox), full = coef(fit_full)) ``` The switch reaches the risk-set averages inside the C++ backend as well as the row weights, so the two halves of the estimator always use the same support. `skmle_cv()` takes it too, so the bandwidth is selected under the same kernel the final fit uses. ## Asynchronous longitudinal data The estimators above model a survival outcome. When the outcome is itself a sparsely observed longitudinal process, measured at times that do **not** line up with the covariate's measurement times, use the kernel-weighted estimating equations of Cao, Zeng and Fine (2015). Nothing is carried forward and no pair is discarded: each (response, covariate) pair contributes in proportion to its time separation. ```{r async-data} set.seed(202) d <- sim_async_data(n = 300, beta = c(0.5, 1.5)) head(d$y, 3) head(d$x, 3) ``` The two tables are deliberately separate. They sit on different grids, so no single data frame holds both without inventing rows. The formula spans both: its left-hand side is looked up in `data_y`, its right-hand side in `data_x`, and `id` and `time` name columns present in each. ```{r async-ti} fit_a <- kee_async(d$y, d$x, y ~ x, id = id, time = time, h = 0.25 ) summary(fit_a) confint(fit_a) ``` To see how the estimate depends on the bandwidth, fit at several values: ```{r async-h} sapply(c(0.10, 0.15, 0.25, 0.40), function(h) coef(kee_async(d$y, d$x, y ~ x, id = id, time = time, h = h))["x"]) ``` If the coefficients themselves vary with time, `kee_async_td()` estimates the curve $\beta(t)$ pointwise. ```{r async-td, fig.width = 7, fig.height = 4} set.seed(203) dt <- sim_async_data( n = 500, 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 `asynchronous` article covers this setting in more detail. ## A typical workflow For routine use, the usual sequence is: 1. Prepare data in long format with one row per observation time. 2. Fit `skmle()` if you want the general transformed hazards model. 3. Use `summary()` and `plot()` to inspect the fitted model. 4. Use `skmle_cv()` to select the bandwidth. 5. Use `kee_cox()` or `kee_additive()` when the scientific model matches those specialized estimators. 6. Use `kee_async()` or `kee_async_td()` when the outcome is longitudinal rather than a survival time. This gives a standard R model-fitting interface while keeping the core numerical work in the Rcpp backend.