## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----remotes-install, eval = FALSE--------------------------------------------
# pak::pkg_install("bdwilliamson/lvimp")

## ----load-lvimp, message = FALSE----------------------------------------------
library("lvimp")

## ----gen-data-----------------------------------------------------------------
set.seed(4747)
p <- 2
n <- 5e4
T <- 3
timepoints <- seq_len(T) - 1
indices <- timepoints + 1
beta_01 <- rep(1, T)
beta_02 <- 1 + timepoints / 4
beta_0 <- lapply(as.list(seq_len(T)), function(t) {
  matrix(c(beta_01[t], beta_02[t]))
})
# generate 2 covariates
x <- lapply(as.list(1:T), function(t) as.data.frame(replicate(p, stats::rnorm(n, 0, 1))))
# apply the function to the x's
y <- lapply(as.list(1:T), function(t) as.matrix(x[[t]]) %*% beta_0[[t]] + rnorm(n, 0, 1))

## ----cross-sectional-vim------------------------------------------------------
library("vimp")
library("SuperLearner")
set.seed(1234)
# in this case, glm is correctly specified (so only use one learner to speed things up)
vim_list_1 <- lapply(as.list(1:T), function(t) {
  vimp::cv_vim(Y = y[[t]], X = x[[t]], indx = 1, V = 10, type = "r_squared",
               SL.library = c("SL.glm"))
})

## ----est-lvim-----------------------------------------------------------------
# set up an lvim object
lvim_obj <- lvim(vim_list_1, timepoints = 1:3)
# obtain the average
est_lvim <- lvim_average(lvim_obj, indices = 1:3)
# add on the linear trend
est_lvim <- lvim_trend(est_lvim, indices = 1:3)
# add on the AUTC based on a piecewise linear trajectory
est_lvim <- lvim_autc(est_lvim, indices = 1:3)
# inspect the estimates
est_lvim

