### Add Examples to Main Estimation Functions Source: https://github.com/nhejazi/txshift/blob/master/docs/news/index.html Includes illustrative examples for the main estimation functions, `txshift` and `vimshift_msm`. This helps users understand how to apply these functions correctly and interpret their outputs. ```R #' @examples #' txshift(data, ...) #' vimshift_msm(data, ...) function_name <- function(...) {} ``` -------------------------------- ### Install txshift and dependencies Source: https://github.com/nhejazi/txshift/blob/master/docs/index.html Commands to install the txshift package from CRAN or GitHub, including the recommended sl3 dependency for ensemble machine learning. ```R install.packages("txshift") remotes::install_github("tlverse/sl3@master") remotes::install_github("nhejazi/txshift@master") remotes::install_github("nhejazi/txshift@devel") ``` -------------------------------- ### Add Examples to Exported Functions Source: https://github.com/nhejazi/txshift/blob/master/docs/news/index.html Begins the process of adding usage examples to all exported functions. This makes the package more user-friendly by providing clear demonstrations of how to use each function. ```R #' @examples #' exported_function(arg1, arg2) exported_function <- function(arg1, arg2) {} ``` -------------------------------- ### Fit Full-Data One-Step Estimator with txshift Source: https://github.com/nhejazi/txshift/blob/master/README.md This example shows how to fit a full-data one-step estimator for comparison purposes using the txshift function. Similar to the TMLE example, it focuses on the counterfactual mean of a shifted treatment without accounting for sampling complexities. ```r os <- txshift( W = W, A = A, Y = Y, delta = 0.5, estimator = "onestep", g_exp_fit_args = list( fit_type = "sl", sl_learners_density = Lrnr_density_hse$new(Lrnr_hal9001$new()) ), Q_fit_args = list(fit_type = "glm", glm_formula = "Y ~ .") ) os ``` -------------------------------- ### Txshift Estimator Examples Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/txshift.html Demonstrates the usage of the txshift function for various causal estimation scenarios. ```APIDOC ## Txshift Estimator Examples ### Description This section provides examples of using the `txshift` function to construct different types of Targeted Maximum Likelihood (TML) estimates, accounting for censoring and two-phase sampling. ### Method `txshift()` ### Endpoint N/A (R function) ### Parameters #### Request Body (Note: These are function arguments, not typical API request body fields) - **W** (data.frame/matrix) - Covariates. - **A** (vector) - Treatment variable. - **C_cens** (vector, optional) - Censoring indicator for outcome. - **Y** (vector) - Outcome variable. - **delta** (numeric) - Threshold for outcome. - **estimator** (string) - Type of estimator (e.g., "onestep"). - **g_exp_fit_args** (list, optional) - Arguments for fitting the treatment mechanism. - **g_cens_fit_args** (list, optional) - Arguments for fitting the censoring mechanism. - **Q_fit_args** (list, optional) - Arguments for fitting the outcome mechanism. - **C_samp** (vector, optional) - Indicator for two-phase sampling. - **V** (vector, optional) - Variables used in two-phase sampling. - **samp_fit_args** (list, optional) - Arguments for fitting the sampling mechanism. - **max_iter** (integer, optional) - Maximum number of iterations. - **eif_reg_type** (string, optional) - Type of regression for EIF. ### Request Example ```R # Construct a TML estimate, accounting for censoring tmle <- txshift( W = W, A = A, C_cens = C_cens, Y = Y, delta = 0.5, estimator = "onestep", g_exp_fit_args = list(fit_type = "hal", n_bins = 3), g_cens_fit_args = list(fit_type = "glm", glm_formula = "C_cens ~ ."), Q_fit_args = list(fit_type = "glm", glm_formula = "Y ~ .") ) # Construct a TML estimate under two-phase sampling, ignoring censoring ipcwtmle <- txshift( W = W, A = A, Y = Y, delta = 0.5, C_samp = C_samp, V = c("W", "Y"), estimator = "onestep", max_iter = 3, samp_fit_args = list(fit_type = "glm"), g_exp_fit_args = list(fit_type = "hal", n_bins = 3), Q_fit_args = list(fit_type = "glm", glm_formula = "Y ~ ."), eif_reg_type = "glm" ) # Construct a TML estimate accounting for two-phase sampling and censoring ipcwtmle <- txshift( W = W, A = A, C_cens = C_cens, Y = Y, delta = 0.5, C_samp = C_samp, V = c("W", "Y"), estimator = "onestep", max_iter = 3, samp_fit_args = list(fit_type = "glm"), g_exp_fit_args = list(fit_type = "hal", n_bins = 3), g_cens_fit_args = list(fit_type = "glm", glm_formula = "C_cens ~ ."), Q_fit_args = list(fit_type = "glm", glm_formula = "Y ~ ."), eif_reg_type = "glm" ) ``` ### Response (Note: The function returns an object containing the TML estimate and related information.) #### Success Response - **estimate** (numeric) - The estimated causal effect. - **variance** (numeric) - The estimated variance of the causal effect. #### Response Example ```json { "estimate": 0.123, "variance": 0.005 } ``` ``` -------------------------------- ### Visualize Marginal Structural Models with plot.txshift_msm Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/plot.txshift_msm.html Demonstrates how to generate a plot for a txshift_msm object. The example includes generating synthetic data, fitting a marginal structural model using msm_vimshift, and visualizing the results with and without a piecewise spline. ```R if (require("sl3")) { set.seed(3287) n_obs <- 1000 W <- as.numeric(replicate(1, rbinom(n_obs, 1, 0.5))) A <- as.numeric(rnorm(n_obs, mean = 2 * W, sd = 1)) Y <- rbinom(n_obs, 1, plogis(2 * A - W)) msm <- msm_vimshift( W = W, A = A, Y = Y, estimator = "tmle", g_exp_fit_args = list( fit_type = "sl", sl_learners_density = Lrnr_density_hse$new(Lrnr_glm$new()) ), Q_fit_args = list( fit_type = "glm", glm_formula = "Y ~ ." ), delta_grid = seq(-1, 1, 0.25) ) plot(msm) # fit a linear spline with knot at 0 set.seed(8293) n_obs <- 1000 W <- as.numeric(replicate(1, rbinom(n_obs, 1, 0.5))) A <- as.numeric(rnorm(n_obs, mean = 2 * W, sd = 1)) Y <- rbinom(n_obs, 1, plogis(0.1 * A * (A >= 0) - 3 * A * (A < 0) - W)) msm <- msm_vimshift( W = W, A = A, Y = Y, estimator = "tmle", g_exp_fit_args = list( fit_type = "sl", sl_learners_density = Lrnr_density_hse$new(Lrnr_glm$new()) ), Q_fit_args = list( fit_type = "glm", glm_formula = "Y ~ ." ), delta_grid = seq(-1, 1, 0.25), msm_form = list(type = "piecewise", knot = 0) ) plot(msm) } ``` -------------------------------- ### Printing txshift Object Summary Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/print.txshift.html This example demonstrates how to perform a stochastic shift intervention analysis using the txshift function and subsequently print the results. It requires the sl3 package for learner configuration and generates a summary output including the estimate and confidence interval. ```R if (require("sl3")) { set.seed(429153) n_obs <- 100 W <- replicate(2, rbinom(n_obs, 1, 0.5)) A <- rnorm(n_obs, mean = 2 * W, sd = 1) Y <- rbinom(n_obs, 1, plogis(A + W + rnorm(n_obs, mean = 0, sd = 1))) txout <- txshift( W = W, A = A, Y = Y, delta = 0.5, estimator = "tmle", g_exp_fit_args = list( fit_type = "sl", sl_learners_density = Lrnr_density_hse$new(Lrnr_glm$new()) ), Q_fit_args = list( fit_type = "glm", glm_formula = "Y ~ ." ) ) print(txout) } ``` -------------------------------- ### Simulate data for txshift analysis Source: https://github.com/nhejazi/txshift/blob/master/README.md Example code to simulate a dataset with covariates, treatment, outcome, and a two-stage sampling process for use with txshift. ```R library(txshift) library(sl3) set.seed(429153) # simulate simple data n_obs <- 500 W <- replicate(2, rbinom(n_obs, 1, 0.5)) A <- rnorm(n_obs, mean = 2 * W, sd = 1) Y <- rbinom(n_obs, 1, plogis(A + W + rnorm(n_obs, mean = 0, sd = 1))) # now, let's introduce a a two-stage sampling process C_samp <- rbinom(n_obs, 1, plogis(W + Y)) ``` -------------------------------- ### TML Estimation Example Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/txshift.html Example R code demonstrating the construction of a Targeted Minimum Loss Estimate (TMLE) for a counterfactual mean, ignoring censoring. It sets up simulated data and specifies fitting arguments for the exposure and outcome mechanisms. ```R set.seed(429153) n_obs <- 100 W <- replicate(2, rbinom(n_obs, 1, 0.5)) A <- rnorm(n_obs, mean = 2 * W, sd = 1) Y <- rbinom(n_obs, 1, plogis(A + W + rnorm(n_obs, mean = 0, sd = 1))) C_samp <- rbinom(n_obs, 1, plogis(W + Y)) # two-phase sampling C_cens <- rbinom(n_obs, 1, plogis(rowSums(W) + 0.5)) # construct a TML estimate, ignoring censoring tmle <- txshift( W = W, A = A, Y = Y, delta = 0.5, estimator = "onestep", g_exp_fit_args = list( fit_type = "hal", n_bins = 3, lambda_seq = exp(seq(-1, -10, length = 50)) ), Q_fit_args = list( fit_type = "glm", ``` -------------------------------- ### Reduce GitHub-Only Dependencies Source: https://github.com/nhejazi/txshift/blob/master/docs/news/index.html Minimizes dependencies that are exclusively available on GitHub, with `sl3` being the primary remaining one. This aims to simplify installation and reduce reliance on non-standard repositories. ```R # DESCRIPTION file updates: # Imports: # sl3 ``` -------------------------------- ### Estimate Counterfactual Mean with IPCW-Augmented One-Step using txshift Source: https://github.com/nhejazi/txshift/blob/master/docs/index.html This code snippet illustrates the use of an IPCW-augmented one-step estimator for estimating the counterfactual mean of a shifted treatment under two-phase sampling. It configures the txshift function with the 'onestep' estimator and specifies arguments for nuisance parameter estimation, similar to the TMLE example. ```R os_ipcw <- txshift( W = W, A = A, Y = Y, delta = 0.5, C_samp = C_samp, V = c("W", "Y"), estimator = "onestep", eif_reg_type = "glm", samp_fit_args = list(fit_type = "glm"), g_exp_fit_args = list( fit_type = "sl", sl_learners_density = Lrnr_density_hse$new(Lrnr_hal9001$new()) ), Q_fit_args = list(fit_type = "glm", glm_formula = "Y ~ .") ) os_ipcw ``` -------------------------------- ### Initialize txshift Environment Source: https://github.com/nhejazi/txshift/blob/master/docs/articles/intro_txshift.html Loads necessary dependencies for causal inference and sets a random seed for reproducible simulations. ```R library(data.table) library(haldensify) library(txshift) set.seed(11249) ``` -------------------------------- ### Printing Marginal Structural Model Results Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/print.txshift_msm.html Demonstrates how to estimate a marginal structural model using msm_vimshift and display the results using the print method. This requires the sl3 package for learner specification. ```R if (require("sl3")) { set.seed(3287) n_obs <- 1000 W <- as.numeric(replicate(1, rbinom(n_obs, 1, 0.5))) A <- as.numeric(rnorm(n_obs, mean = 2 * W, sd = 1)) Y <- rbinom(n_obs, 1, plogis(2 * A - W)) msm <- msm_vimshift( W = W, A = A, Y = Y, estimator = "tmle", g_exp_fit_args = list( fit_type = "sl", sl_learners_density = Lrnr_density_hse$new(Lrnr_glm$new()) ), Q_fit_args = list( fit_type = "glm", glm_formula = "Y ~ ." ), delta_grid = seq(-1, 1, 0.25) ) print(msm) } ``` -------------------------------- ### Configure Ensemble Machine Learning Learners with sl3 (R) Source: https://github.com/nhejazi/txshift/blob/master/docs/articles/intro_txshift.html Sets up ensemble machine learning learners using the sl3 R package for use in causal inference tasks. It defines various learners (mean, GLM, ranger) and stacks them for outcome regression (Q_lib) and density estimation (g_lib), utilizing different metalearners for optimal performance. ```R library(sl3) # SL learners to be used for most fits (e.g., IPCW, outcome regression) mean_learner <- Lrnr_mean$new() glM_learner <- Lrnr_glm$new() rf_learner <- Lrnr_ranger$new() Q_lib <- Stack$new(mean_learner, glm_learner, rf_learner) sl_learner <- Lrnr_sl$new(learners = Q_lib, metalearner = Lrnr_nnls$new()) # SL learners for fitting the generalized propensity score fit hose_learner <- make_learner(Lrnr_density_semiparametric, mean_learner = glm_learner ) hese_learner <- make_learner(Lrnr_density_semiparametric, mean_learner = rf_learner, var_learner = glm_learner ) g_lib <- Stack$new(hose_learner, hese_learner) sl_learner_density <- Lrnr_sl$new( learners = g_lib, metalearner = Lrnr_solnp_density$new() ) ``` -------------------------------- ### txshift Function Documentation Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/txshift.html Detailed documentation for the main txshift function, explaining its parameters and usage for estimating counterfactual means. ```APIDOC ## txshift Function ### Description Efficiently estimates the counterfactual mean of a stochastic shift intervention. ### Method R Function ### Endpoint N/A (R function) ### Parameters #### Arguments - **W** (matrix, data.frame) - A set of baseline covariates. - **A** (numeric vector) - A treatment variable. The parameter of interest is defined as a location shift of this quantity. - **C_cens** (numeric vector) - Indicator for censoring due to loss to follow-up. Defaults to all 1s (no censoring). - **Y** (numeric vector) - The observed outcomes. - **C_samp** (numeric vector) - Indicator for censoring due to being omitted from a second-stage sample. Defaults to all 1s (no censoring). - **V** (NULL, character vector, data.table) - Covariates used in determining the sampling procedure for `C_samp`. Defaults to NULL. - **delta** (numeric) - The shift in the treatment for defining the target parameter. - **estimator** (character) - Type of estimator: "tmle" (targeted maximum likelihood) or "onestep" (one-step). - **fluctuation** (character) - Method for submodel fluctuation in TML estimation: "standard" or "weighted". - **max_iter** (numeric integer) - Maximum number of iterations for convergence. - **gps_bound** (numeric) - Lower limit for generalized propensity score estimates (default = 0.01). - **samp_fit_args** (list) - Arguments passed to `est_samp` for fitting the sampling mechanism. - **g_exp_fit_args** (list) - Arguments passed to `est_g_exp` for fitting the exposure mechanism. - **g_cens_fit_args** (list) - Arguments passed to `est_g_cens` for fitting the censoring mechanism. - **Q_fit_args** (list) - Arguments passed to `est_Q` for fitting the outcome model. - **eif_reg_type** (character) - Type of regression for the efficient influence function: "hal" or "glm". - **ipcw_efficiency** (logical) - Whether to use inverse probability of censoring weights for efficiency. - **samp_fit_ext** (external) - User-specified fit for the sampling mechanism. - **gn_exp_fit_ext** (external) - User-specified fit for the exposure mechanism. - **gn_cens_fit_ext** (external) - User-specified fit for the censoring mechanism. - **Qn_fit_ext** (external) - User-specified fit for the outcome model. ### Request Example ```R txshift( W = my_covariates, A = my_treatment, Y = my_outcomes, delta = 1 ) ``` ### Response #### Success Response (200) Returns an object containing the estimated counterfactual mean and related statistics. #### Response Example ```R # Example output structure (actual values will vary) list( mean_counterfactual = 10.5, std_error = 1.2 ) ``` ``` -------------------------------- ### Summarize txshift object in R Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/summary.txshift.html Demonstrates how to generate data, perform a stochastic shift intervention using the txshift function, and output a summary of the results including confidence intervals. ```R set.seed(429153) n_obs <- 100 W <- replicate(2, rbinom(n_obs, 1, 0.5)) A <- rnorm(n_obs, mean = 2 * W, sd = 1) Y <- rbinom(n_obs, 1, plogis(A + W + rnorm(n_obs, mean = 0, sd = 1))) txout <- txshift( W = W, A = A, Y = Y, delta = 0.5, estimator = "tmle", g_exp_fit_args = list( fit_type = "hal", n_bins = 5, grid_type = "equal_mass", lambda_seq = exp(-1:-9) ), Q_fit_args = list( fit_type = "glm", glm_formula = "Y ~ ." ) ) summary(txout) ``` -------------------------------- ### S3 method: summary.txshift Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/summary.txshift.html Prints a summary of the counterfactual mean stochastic shift intervention results, including parameter estimates, confidence intervals, and variance. ```APIDOC ## S3 method: summary(object, ...) ### Description Provides a summary of the results from a stochastic shift intervention analysis, specifically for objects of class `txshift`. ### Method S3 Generic Method ### Parameters #### Arguments - **object** (txshift) - Required - An object of class `txshift` produced by the `txshift()` function. - **ci_level** (numeric) - Optional - The confidence level for the interval calculation (default: 0.95). - **digits** (numeric) - Optional - The number of digits to round the output (default: 4). ### Request Example summary(txout, ci_level = 0.95, digits = 4) ### Response #### Success Response (Side Effect) - **lwr_ci** (numeric) - Lower bound of the confidence interval. - **param_est** (numeric) - The estimated parameter value. - **upr_ci** (numeric) - Upper bound of the confidence interval. - **param_var** (numeric) - Variance of the parameter estimate. - **eif_mean** (numeric) - Mean of the efficient influence function. - **estimator** (string) - The type of estimator used (e.g., "tmle"). - **n_iter** (integer) - Number of iterations performed. ``` -------------------------------- ### Bound Propensity Scores with txshift Source: https://context7.com/nhejazi/txshift/llms.txt Demonstrates how to bound propensity score estimates to prevent extreme weights. It uses the bound_propensity function to ensure values do not fall below a specified threshold or 1/n. ```R gps_estimates <- c(0.001, 0.05, 0.15, 0.30, 0.45, 0.002) bounded_gps <- bound_propensity(gps_estimates, bound = 0.01) print(bounded_gps) ``` -------------------------------- ### Constructing Confidence Intervals with txshift Source: https://github.com/nhejazi/txshift/blob/master/docs/articles/intro_txshift.html Demonstrates how to generate Wald-type confidence intervals for a causal effect estimator using the confint method. ```R (ci_est_shift <- confint(est_shift)) ``` -------------------------------- ### Add Roxygen Details and Return Slots to Functions Source: https://github.com/nhejazi/txshift/blob/master/docs/news/index.html Enhances documentation by adding 'details' and 'return' slots to Roxygen comments for various functions. This provides more comprehensive information about function behavior, parameters, and return values, improving usability. ```R #' @details More detailed explanation of the function. #' @return Description of the returned object. function_name <- function(...) {} ``` -------------------------------- ### Improve Argument Names and Update Documentation Source: https://github.com/nhejazi/txshift/blob/master/docs/news/index.html Enhances clarity by improving argument names in functions and updating associated documentation. This makes the package easier to understand and use. ```R # Function arguments have been renamed for clarity. # Documentation reflects these changes. ``` -------------------------------- ### S3 print.txshift Method Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/print.txshift.html Prints a summary of the counterfactual mean estimate, including the intervention type, estimator used, point estimate, standard error, and confidence intervals. ```APIDOC ## S3 print.txshift ### Description Prints an informative summary of the slots of objects of class 'txshift', representing the counterfactual mean of a stochastic shift intervention. ### Method S3 Method (print) ### Parameters #### Arguments - **x** (txshift object) - Required - An object of class 'txshift' containing the results of the intervention analysis. - **...** (dots) - Optional - Additional options (not currently used). - **ci_level** (numeric) - Optional - A numeric value indicating the confidence level for the interval (default is 0.95). ### Request Example print(txout, ci_level = 0.95) ### Response #### Success Response - **Output** (Console) - Prints the Counterfactual Mean, Intervention details, Estimator type, Estimate, Std. Error, and Confidence Interval. #### Response Example Counterfactual Mean of Shifted Treatment Intervention: Treatment + 0.5 txshift Estimator: tmle Estimate: 0.7876 Std. Error: 0.0387 95% CI: [0.702, 0.8538] ``` -------------------------------- ### MSM Summarization Class and Plot Method (msm_vimshift) Source: https://github.com/nhejazi/txshift/blob/master/docs/news/index.html Adds a dedicated S3 class and a `plot` method for MSM summarization results generated by `msm_vimshift`. This facilitates easier visualization and interpretation of MSM outputs. The `plot` method likely leverages the structure of the new class to generate informative graphics. ```R msm_results <- msm_vimshift(...) plot(msm_results) ``` -------------------------------- ### Add Unit Tests for MSM and Nuisance Parameter Estimation Source: https://github.com/nhejazi/txshift/blob/master/docs/news/index.html Introduces unit tests specifically for the Marginal Structural Model (MSM) functionality and the estimation of nuisance parameters. These tests ensure the correctness and robustness of these critical components of the package. ```R library(testthat) test_that("MSM estimation is correct", { # ... test code ... }) test_that("Nuisance parameter estimation is correct", { # ... test code ... }) ``` -------------------------------- ### Update Documentation and Lock Dependency Versions Source: https://github.com/nhejazi/txshift/blob/master/docs/news/index.html Involves extensive updates to package documentation and locking specific versions for dependencies, such as `sl3` (>= v1.3.6) and `hal9001` (>= v0.2.5). This ensures consistency and reproducibility. ```R # DESCRIPTION file updates: # Imports: # sl3 (>= 1.3.6) # hal9001 (>= 0.2.5) ``` -------------------------------- ### Efficient Effect Estimation with Super Learning (sl3) Source: https://github.com/nhejazi/txshift/blob/master/docs/articles/intro_txshift.html This snippet demonstrates how to use the txshift function with the 'sl' fit_type to leverage the Super Learner algorithm from the sl3 package for fitting nuisance functions. It's suitable for efficient effect estimation when complex prediction models are needed. ```R est_shift_sl <- txshift( W = W, A = A, Y = Y, delta = delta, g_exp_fit_args = list( fit_type = "sl", sl_learners_density = sl_learner_density ), Q_fit_args = list( fit_type = "sl", sl_learners = sl_learner ) ) est_shift_sl ``` -------------------------------- ### Compute Confidence Intervals for txshift Objects Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/confint.txshift.html Demonstrates how to generate a txshift object using TMLE and subsequently compute the confidence interval for the counterfactual mean estimate. ```R set.seed(429153) n_obs <- 100 W <- replicate(2, rbinom(n_obs, 1, 0.5)) A <- rnorm(n_obs, mean = 2 * W, sd = 1) Y <- rbinom(n_obs, 1, plogis(A + W + rnorm(n_obs, mean = 0, sd = 1))) txout <- txshift( W = W, A = A, Y = Y, delta = 0.5, estimator = "tmle", g_exp_fit_args = list( fit_type = "hal", n_bins = 5, grid_type = "equal_mass", lambda_seq = exp(-1:-9) ), Q_fit_args = list( fit_type = "glm", glm_formula = "Y ~ ." ) ) confint(txout) ``` -------------------------------- ### Fit Full-Data TMLE with txshift Source: https://github.com/nhejazi/txshift/blob/master/README.md This snippet demonstrates fitting a full-data Targeted Maximum Likelihood Estimation (TMLE) for the counterfactual mean of a shifted treatment. It utilizes the txshift function with specified arguments for outcome and treatment models, ignoring two-phase sampling. ```r tmle <- txshift( W = W, A = A, Y = Y, delta = 0.5, estimator = "tmle", g_exp_fit_args = list( fit_type = "sl", sl_learners_density = Lrnr_density_hse$new(Lrnr_hal9001$new()) ), Q_fit_args = list(fit_type = "glm", glm_formula = "Y ~ .") ) tmle ``` -------------------------------- ### Estimating Effects with Two-Phase Sampling (txshift) Source: https://github.com/nhejazi/txshift/blob/master/docs/articles/intro_txshift.html This code illustrates the use of the txshift function for estimating causal effects in case-cohort studies with two-phase sampling. It shows how to specify additional arguments like C_samp, V, samp_fit_args, and eif_reg_type to account for the sampling mechanism and use different regression types like HAL or GLM. ```R est_shift_ipcw <- txshift( W = W, A = A, Y = Y, delta = delta, C_samp = Delta_samp, V = c("W", "Y"), samp_fit_args = list(fit_type = "glm"), g_exp_fit_args = list( fit_type = "hal", n_bins = 5, grid_type = "equal_mass", lambda_seq = exp(seq(-1, -10, length = 100)) ), Q_fit_args = list( fit_type = "glm", glm_formula = "Y ~ .^2" ), eif_reg_type = "glm" ) est_shift_ipcw ``` -------------------------------- ### Estimate Causal Effects with msm_vimshift Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/msm_vimshift.html This snippet demonstrates the initialization and execution of the msm_vimshift function. It includes data simulation for covariates, treatment, and outcomes, followed by fitting a marginal structural model with a piecewise linear spline. ```R n_obs <- 100 W <- as.numeric(replicate(1, rbinom(n_obs, 1, 0.5))) A <- as.numeric(rnorm(n_obs, mean = 2 * W, sd = 1)) Y <- rbinom(n_obs, 1, plogis(0.1 * A * (A >= 0) - 3 * A * (A < 0) - W)) msm <- msm_vimshift( W = W, A = A, Y = Y, estimator = "tmle", g_exp_fit_args = list( fit_type = "sl", sl_learners_density = Lrnr_density_hse$new(Lrnr_glm$new()) ), Q_fit_args = list( fit_type = "glm", glm_formula = "Y ~ ." ), delta_grid = seq(-1, 1, 0.25), msm_form = list(type = "piecewise", knot = 0) ) ``` -------------------------------- ### Estimate with Super Learner using txshift Source: https://context7.com/nhejazi/txshift/llms.txt Estimates causal effects using the txshift function with Super Learner (`sl3` package) for flexible estimation of nuisance parameters (outcome regression and density estimation). This allows for complex, data-driven modeling of these components. ```r library(txshift) library(sl3) set.seed(11249) n_obs <- 500 W <- rbinom(n_obs, 1, 0.5) A <- rnorm(n_obs, mean = 2 * W, sd = 0.5) Y <- A + W + rnorm(n_obs, mean = 0, sd = 1) # Define Super Learner for outcome regression mean_learner <- Lrnr_mean$new() glm_learner <- Lrnr_glm$new() rf_learner <- Lrnr_ranger$new() Q_lib <- Stack$new(mean_learner, glm_learner, rf_learner) sl_learner <- Lrnr_sl$new(learners = Q_lib, metalearner = Lrnr_nnls$new()) # Define Super Learner for conditional density (generalized propensity score) hose_learner <- make_learner(Lrnr_density_semiparametric, mean_learner = glm_learner ) hese_learner <- make_learner(Lrnr_density_semiparametric, mean_learner = rf_learner, var_learner = glm_learner ) g_lib <- Stack$new(hose_learner, hese_learner) sl_learner_density <- Lrnr_sl$new( learners = g_lib, metalearner = Lrnr_solnp_density$new() ) # Fit with Super Learner est_sl <- txshift( W = W, A = A, Y = Y, delta = 0.5, estimator = "tmle", g_exp_fit_args = list( fit_type = "sl", sl_learners_density = sl_learner_density ), Q_fit_args = list( fit_type = "sl", sl_learners = sl_learner ) ) ``` -------------------------------- ### Refactor LM Model Object Creation in msm_vimshift Source: https://github.com/nhejazi/txshift/blob/master/docs/news/index.html Addresses a bug in `msm_vimshift` concerning the creation of `lm` model objects, particularly through weighted regression. Models are now moved from the `plot` method directly into `msm_vimshift`, streamlining the process and ensuring consistency. ```R msm_vimshift(..., model_type = "lm", weighted = TRUE) ``` -------------------------------- ### Estimate Counterfactual Mean with IPCW-TMLE using txshift Source: https://github.com/nhejazi/txshift/blob/master/docs/index.html This code snippet demonstrates how to fit an IPCW-TMLE model to estimate the counterfactual mean of a shifted treatment. It accounts for a two-phase sampling process and specifies various arguments for the txshift function, including estimator type, maximum iterations, and regression types for nuisance parameters. ```R tmle_ipcw <- txshift( W = W, A = A, Y = Y, delta = 0.5, C_samp = C_samp, V = c("W", "Y"), estimator = "tmle", max_iter = 5, eif_reg_type = "glm", samp_fit_args = list(fit_type = "glm"), g_exp_fit_args = list( fit_type = "sl", sl_learners_density = Lrnr_density_hse$new(Lrnr_hal9001$new()) ), Q_fit_args = list(fit_type = "glm", glm_formula = "Y ~ .") ) tmle_ipcw ``` -------------------------------- ### POST /msm_vimshift Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/msm_vimshift.html Calculates counterfactual means for a grid of shift parameters and fits a working marginal structural model. ```APIDOC ## POST /msm_vimshift ### Description Computes estimates of the counterfactual mean over a grid of shift stochastic interventions and fits a working marginal structural model to summarize the trend through the counterfactual means as a function of the specified shift intervention. ### Method POST ### Endpoint /msm_vimshift ### Parameters #### Request Body - **W** (matrix/data.frame) - Required - Baseline covariates. - **A** (numeric vector) - Required - Treatment variable. - **Y** (numeric vector) - Required - Observed outcomes. - **C_cens** (numeric vector) - Optional - Indicator for censoring due to loss to follow-up. - **C_samp** (numeric vector) - Optional - Indicator for censoring due to two-phase sampling. - **V** (list) - Optional - Covariates defining the sampling/censoring mechanism. - **delta_grid** (numeric vector) - Optional - Values of the shift parameter. - **msm_form** (list) - Optional - Specification for the working MSM (type and knot). - **estimator** (string) - Optional - Type of estimator: "tmle" or "onestep". - **weighting** (string) - Optional - Weighting scheme: "identity" or "variance". ### Request Example { "W": [0, 1, 0, 1], "A": [1.2, 0.5, 2.1, 0.8], "Y": [0, 1, 0, 1], "estimator": "tmle", "delta_grid": [-0.5, 0, 0.5] } ### Response #### Success Response (200) - **estimates** (list) - Individual counterfactual means over the grid. - **msm_fit** (object) - The fitted marginal structural model parameters. #### Response Example { "estimates": [0.45, 0.52, 0.58], "msm_fit": { "coef": [0.5, 0.1], "type": "linear" } } ``` -------------------------------- ### Estimate causal effects with txshift Source: https://github.com/nhejazi/txshift/blob/master/docs/index.html Demonstrates simulating data and using the txshift function to compute TMLE and one-step estimators for a stochastic intervention. ```R library(txshift) library(sl3) set.seed(429153) n_obs <- 500 W <- replicate(2, rbinom(n_obs, 1, 0.5)) A <- rnorm(n_obs, mean = 2 * W, sd = 1) Y <- rbinom(n_obs, 1, plogis(A + W + rnorm(n_obs, mean = 0, sd = 1))) tmle <- txshift( W = W, A = A, Y = Y, delta = 0.5, estimator = "tmle", g_exp_fit_args = list( fit_type = "sl", sl_learners_density = Lrnr_density_hse$new(Lrnr_hal9001$new()) ), Q_fit_args = list(fit_type = "glm", glm_formula = "Y ~ .") ) print(tmle) ``` -------------------------------- ### Estimate Exposure Mechanism with Generalized Propensity Score (R) Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/est_g_exp.html Estimates the generalized propensity score for observed and shifted exposure levels. It can utilize Super Learner or Highly Adaptive Lasso for density estimation. Dependencies include the 'sl3' and 'hal9001' packages for model fitting. ```R est_g_exp( A, W, delta = 0, samp_weights = rep(1, length(A)), fit_type = c("hal", "sl"), sl_learners_density = NULL, haldensify_args = list(grid_type = "equal_range", lambda_seq = exp(seq(-1, -13, length = 300))) ) ``` -------------------------------- ### POST /onestep_txshift Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/index.html Computes the one-step estimate of the counterfactual mean under a stochastic shift intervention. ```APIDOC ## POST /onestep_txshift ### Description Computes the one-step estimate of the counterfactual mean of a stochastic shift intervention, providing a robust estimator for causal effects. ### Method POST ### Endpoint /onestep_txshift ### Parameters #### Request Body - **W** (matrix) - Required - Baseline covariates - **A** (numeric) - Required - Exposure/treatment vector - **Y** (numeric) - Required - Outcome vector - **delta** (numeric) - Required - The shift parameter for the intervention ### Request Example { "W": [[0.5, 1.2], [0.2, 0.8]], "A": [0, 1], "Y": [10, 15], "delta": 0.5 } ### Response #### Success Response (200) - **estimate** (numeric) - The calculated one-step estimate - **se** (numeric) - Standard error of the estimate #### Response Example { "estimate": 12.4, "se": 0.15 } ``` -------------------------------- ### Estimate Causal Effects with External Nuisance Parameters Source: https://context7.com/nhejazi/txshift/llms.txt Shows how to bypass internal estimation by providing pre-computed sampling mechanisms, treatment mechanisms (generalized propensity scores), and outcome regressions to the txshift function. ```R est_external <- txshift( W = W, A = A, Y = Y, delta = delta, samp_fit_args = list(fit_type = "external"), samp_fit_ext = ipcw_out, g_exp_fit_args = list(fit_type = "external"), gn_exp_fit_ext = gn_out, Q_fit_args = list(fit_type = "external"), Qn_fit_ext = Qn_out ) ``` -------------------------------- ### Add Tighter Unit Tests for One-Step and TML Estimators Source: https://github.com/nhejazi/txshift/blob/master/docs/news/index.html Introduces more rigorous unit tests for both one-step and Targeted Maximum Likelihood Estimators (TMLE). These enhanced tests aim to ensure the accuracy and reliability of the core estimation procedures. ```R library(testthat) test_that("One-step estimator is accurate", { # ... detailed test code ... }) test_that("TMLE estimator is accurate", { # ... detailed test code ... }) ``` -------------------------------- ### Add Safety Checks for Fluctuation Regression Convergence Source: https://github.com/nhejazi/txshift/blob/master/docs/news/index.html Incorporates safety checks for the convergence of fluctuation regressions, drawing inspiration from similar checks in the `drtmle` and `survtmle` packages. This enhances the robustness of the estimation process by detecting and handling non-convergence. ```R # Fluctuation regression convergence checks added. ``` -------------------------------- ### POST /tmle_txshift Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/index.html Computes the Targeted Minimum Loss Estimate (TMLE) of the counterfactual mean under a stochastic shift intervention. ```APIDOC ## POST /tmle_txshift ### Description Performs Targeted Minimum Loss Estimation to estimate the counterfactual mean, accounting for potential bias in initial estimates. ### Method POST ### Endpoint /tmle_txshift ### Parameters #### Request Body - **W** (matrix) - Required - Baseline covariates - **A** (numeric) - Required - Exposure/treatment vector - **Y** (numeric) - Required - Outcome vector - **delta** (numeric) - Required - The shift parameter ### Request Example { "W": [[0.5, 1.2], [0.2, 0.8]], "A": [0, 1], "Y": [10, 15], "delta": 0.5 } ### Response #### Success Response (200) - **tmle_estimate** (numeric) - The TMLE estimate - **var_influence** (numeric) - Variance of the influence function #### Response Example { "tmle_estimate": 12.35, "var_influence": 0.02 } ``` -------------------------------- ### Print Method for Marginal Structural Models Source: https://github.com/nhejazi/txshift/blob/master/docs/reference/print.txshift_msm.html This section details the `print.txshift_msm` function, which is an S3 method for printing objects of class `txshift_msm`. It displays an informative summary of the model's slots. ```APIDOC ## Print Method for Marginal Structural Models ### Description This S3 method for the `txshift_msm` class prints a summary of the Marginal Structural Model. ### Method S3 Method (`print.txshift_msm`) ### Endpoint N/A (This is an R function, not a web API endpoint) ### Parameters #### Arguments - **x** (`txshift_msm`) - Required - An object of class `txshift_msm`. - **...** (any) - Optional - Other options (not currently used). ### Request Example ```R if (require("sl3")) { set.seed(3287) n_obs <- 1000 W <- as.numeric(replicate(1, rbinom(n_obs, 1, 0.5))) A <- as.numeric(rnorm(n_obs, mean = 2 * W, sd = 1)) Y <- rbinom(n_obs, 1, plogis(2 * A - W)) msm <- msm_vimshift( W = W, A = A, Y = Y, estimator = "tmle", g_exp_fit_args = list( fit_type = "sl", sl_learners_density = Lrnr_density_hse$new(Lrnr_glm$new()) ), Q_fit_args = list( fit_type = "glm", glm_formula = "Y ~ ." ), delta_grid = seq(-1, 1, 0.25) ) print(msm) } ``` ### Response #### Output (Console) - The printed output provides a summary of the MSM, including the intervention grid, estimator type, estimated slope, standard error, confidence interval, and p-value. #### Response Example ``` MSM (linear) for Grid of Shifted Treatments Intervention Grid: Treatment + {-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1} txshift MSM Estimator: tmle Estimated Slope: 0.2114 Std. Error: 0.0095 95% CI: [0.1928, 0.2301] p-value (vs. no trend): 0 ``` ``` -------------------------------- ### Update Estimation Terminology and Add Roxygen Slots Source: https://github.com/nhejazi/txshift/blob/master/docs/news/index.html Revises the terminology used for estimation, changing from 'AIPW' to 'one-step', and enhances documentation by adding Roxygen 'details' and 'return' slots. This improves clarity and adherence to standard statistical language. ```R #' @details Uses the one-step estimation approach. #' @return Estimated treatment effect. function_name <- function(...) {} ```