### Imbalanced Classification Setup Source: https://context7.com/kogalur/randomforestsrc/llms.txt Prepares the breast cancer dataset for imbalanced classification by removing NAs and defining the formula. Requires 'randomForestSRC' package. ```R data(breast, package = "randomForestSRC") breast <- na.omit(breast) f <- as.formula(status ~ .) ``` -------------------------------- ### Standard RF with G-mean performance Source: https://context7.com/kogalur/randomforestsrc/llms.txt This example demonstrates training a standard random forest model and specifying G-mean as the performance type using the `perf.type = "gmean"` argument. ```r o.std <- imbalanced(f, breast, method = "stand", perf.type = "gmean") ``` -------------------------------- ### Confidence intervals for G-mean VIMP via subsampling Source: https://context7.com/kogalur/randomforestsrc/llms.txt This example shows how to compute confidence intervals for G-mean Variable Importance (VIMP) using subsampling. It requires the `caret` package and demonstrates generating simulated data, training a model, performing subsampling, and plotting the results. ```r if (requireNamespace("caret", quietly = TRUE)) { library(caret) n <- 1000; q <- 20; ir <- 6 d <- twoClassSim(n, linearVars = 15, noiseVars = q) d$Class <- factor(as.numeric(d$Class) - 1) idx.min <- sample(which(d$Class == 1), sum(d$Class == 1) / ir, replace = FALSE) d <- d[c(which(d$Class == 0), idx.min), ] o <- imbalanced(Class ~ ., d, importance = "permute", block.size = 10) smp.o <- subsample(o, B = 100) plot(smp.o, cex.axis = 0.7) } ``` -------------------------------- ### Compare SID, Shi-Horvath, and Unsupervised Clustering on Glass Data Source: https://context7.com/kogalur/randomforestsrc/llms.txt Compares SID, Shi-Horvath, and plain unsupervised clustering methods on the Glass dataset from the mlbench package. Requires the mlbench package to be installed. Prints contingency tables and performance metrics for each method. ```r if (requireNamespace("mlbench", quietly = TRUE)) { data(Glass, package = "mlbench") glass <- Glass; y <- Glass$Type; glass$Type <- NULL o.sid <- sidClustering(glass, k = 6) o.sh <- sidClustering(glass, method = "sh1", k = 6) o.un <- sidClustering(glass, method = "unsupv", k = 6) print(table(y, o.sid$cl)); print(sid.perf.metric(y, o.sid$cl)) print(table(y, o.sh$cl)); print(sid.perf.metric(y, o.sh$cl)) print(table(y, o.un$cl)); print(sid.perf.metric(y, o.un$cl)) } ``` -------------------------------- ### Fast Approximate Random Forest for Classification Source: https://context7.com/kogalur/randomforestsrc/llms.txt This example uses `rfsrc.fast` for a classification task on the wine dataset. It converts the quality variable to a factor and then trains the model. ```r data(wine, package = "randomForestSRC") wine$quality <- factor(wine$quality) o <- rfsrc.fast(quality ~ ., wine) print(o) ``` -------------------------------- ### Maximal Subtree for Competing Risks Analysis Source: https://context7.com/kogalur/randomforestsrc/llms.txt This example demonstrates using `max.subtree` for competing risks analysis. It calculates minimal depth for the overall forest and event-specific Variable Importance (VIMP) using `rfsrc` with `splitrule = "logrankCR"`. The results are combined and printed. ```r if (requireNamespace("survival", quietly = TRUE)) { data(pbc, package = "survival") pbc$id <- NULL pbc.cr <- rfsrc(Surv(time, status) ~ ., pbc) pbc.log1 <- rfsrc(Surv(time, status) ~ ., pbc, splitrule = "logrankCR", cause = c(1,0), importance = TRUE) pbc.log2 <- rfsrc(Surv(time, status) ~ ., pbc, splitrule = "logrankCR", cause = c(0,1), importance = TRUE) var.perf <- data.frame( md = max.subtree(pbc.cr)$order[, 1], vimp1 = 100 * pbc.log1$importance[, 1], vimp2 = 100 * pbc.log2$importance[, 2] ) print(var.perf[order(var.perf$md), ], digits = 2) } ``` -------------------------------- ### Targeted Holdout VIMP for Specific Variables Source: https://context7.com/kogalur/randomforestsrc/llms.txt Performs targeted holdout Variable Importance (VIMP) analysis for a specified subset of variables. Only variables 3 and 4 are considered in this example. ```r vtry <- list(xvar = c(3, 4), joint = FALSE) print(holdout.vimp(Species ~ ., data = iris, vtry = vtry)$importance) ``` -------------------------------- ### Maximal Subtree for Survival Variable Selection Source: https://context7.com/kogalur/randomforestsrc/llms.txt This example uses `max.subtree` to extract maximal subtree information from a trained survival random forest model (`v.obj`). It prints the first and second-order depths, the depth threshold, and the selected top variables. ```r data(veteran, package = "randomForestSRC") v.obj <- rfsrc(Surv(time, status) ~ ., data = veteran) v.max <- max.subtree(v.obj) print(round(v.max$order, 3)) # first and second-order depths print(v.max$threshold) # depth threshold for strong variables print(v.max$topvars) # selected variables ``` -------------------------------- ### Quantile Regression with Train/Test Split Source: https://context7.com/kogalur/randomforestsrc/llms.txt Demonstrates training a quantile regression forest on a subset of mtcars and then predicting on a test set. Requires the 'randomForestSRC' package. ```R ## Train / test split o.train <- quantreg(mpg ~ ., mtcars[1:20, ]) o.test <- quantreg(object = o.train, newdata = mtcars[-(1:20), ]) print(get.quantile(o.test)) print(get.quantile.stat(o.test)) ``` -------------------------------- ### Outcome-Guided Random Forest Imputation Source: https://context7.com/kogalur/randomforestsrc/llms.txt Performs imputation of missing values guided by an outcome variable using random forests. Requires the 'randomForestSRC' package and a formula specifying the outcome. ```r f <- as.formula(Surv(days, status) ~ .) pbc2.d <- impute(f, data = pbc, nsplit = 3) ``` -------------------------------- ### Quantile Regression with Forest Weights Method Source: https://context7.com/kogalur/randomforestsrc/llms.txt Applies quantile regression to the Boston Housing dataset using the 'forest' method and plots conditional quantiles. Requires 'mlbench' and 'randomForestSRC' packages. ```R ## Boston Housing with forest-weights method if (requireNamespace("mlbench", quietly = TRUE)) { data(BostonHousing, package = "mlbench") o <- quantreg(medv ~ ., BostonHousing, method = "forest", nodesize = 1) plot.quantreg(o, 0.05, 0.95) quant.dat <- get.quantile(o, c(0.25, 0.50, 0.75)) quant.stat <- get.quantile.stat(o) print(head(data.frame(quant.dat[, -2], q25.normal = quant.stat$mean + qnorm(0.25) * quant.stat$std, q75.normal = quant.stat$mean + qnorm(0.75) * quant.stat$std))) } ``` -------------------------------- ### Quantile Regression with Greenwald-Khanna Algorithm Source: https://context7.com/kogalur/randomforestsrc/llms.txt Uses the Greenwald-Khanna ('gk') method for quantile regression on a large housing dataset, suitable for memory-constrained environments. Requires 'randomForestSRC' package. ```R ## Greenwald-Khanna for large data data(housing, package = "randomForestSRC") housing <- impute(SalePrice ~ ., housing, ntree = 50, nimpute = 1, splitrule = "random") o.gk <- quantreg(SalePrice ~ ., housing, method = "gk", prob = (1:20) / 20, prob.epsilon = 1/20, ntree = 250) plot.quantreg(o.gk) ``` -------------------------------- ### Save and Reload Predictive Imputer Source: https://context7.com/kogalur/randomforestsrc/llms.txt Demonstrates saving a trained predictive imputer to disk and reloading it for later use. Requires the 'fst' package and 'randomForestSRC' package. ```r ## Save and reload the imputer (requires fst package) ## bundle.dir <- file.path(tempdir(), "my.imputer") ## save.impute.learn(fit, bundle.dir) ## imp <- load.impute.learn(bundle.dir, lazy = TRUE) ## test.imp2 <- predict(imp, test) ``` -------------------------------- ### Fast backend for imbalanced data Source: https://context7.com/kogalur/randomforestsrc/llms.txt This snippet shows how to use the fast backend for the `imbalanced` function by setting `fast = TRUE`. This is useful for handling imbalanced data more efficiently. ```r data(breast, package = "randomForestSRC") breast <- na.omit(breast) o <- imbalanced(status ~ ., breast, fast = TRUE) print(o) ``` -------------------------------- ### Hyperparameter Tuning for Class Imbalance (RFQ) Source: https://context7.com/kogalur/randomforestsrc/llms.txt Tunes hyperparameters for a Random Forest Quantile (RFQ) model on an imbalanced breast cancer dataset, optimizing for G-mean. Requires 'randomForestSRC' package. ```R ## Tuning for class imbalance (RFQ with G-mean) data(breast, package = "randomForestSRC") breast <- na.omit(breast) o.rfq <- tune(status ~ ., data = breast, rfq = TRUE, perf.type = "gmean", method = "golden", seed = 1) print(o.rfq$optimal) ``` -------------------------------- ### Hyperparameter Tuning: Grid Search Source: https://context7.com/kogalur/randomforestsrc/llms.txt Tunes 'nodesize' and 'mtry' hyperparameters for a random forest classification model on the wine dataset using a grid search method. Requires 'randomForestSRC' package. ```R data(wine, package = "randomForestSRC") wine$quality <- factor(wine$quality) ## Grid search over nodesize and mtry o1 <- tune(quality ~ ., wine, sampsize = 100, method = "grid") print(o1$optimal) # named vector: nodesize = X, mtry = Y ``` -------------------------------- ### Hyperparameter Tuning: Nodesize-Only Search Source: https://context7.com/kogalur/randomforestsrc/llms.txt Performs a one-dimensional grid search specifically for the 'nodesize' hyperparameter on the wine dataset. Requires 'randomForestSRC' package. ```R ## Nodesize-only tuning o3 <- tune.nodesize(quality ~ ., wine, sampsize = 100, method = "grid", trace = TRUE, seed = 1) plot(o3$err, type = "s", xlab = "nodesize", ylab = "OOB Error") ``` -------------------------------- ### Grow a Random Forest with rfsrc Source: https://context7.com/kogalur/randomforestsrc/llms.txt The main entry point for fitting various types of random forests. The family is inferred from the formula and data. Supports OpenMP, multiple splitting rules, bootstrap strategies, and optional variable importance computation. ```r library(randomForestSRC) ## --- Regression --- airq.obj <- rfsrc(Ozone ~ ., data = airquality, na.action = "na.impute") print(airq.obj) # Sample size: 153 | OOB MSE: ~310 | R^2 OOB: ~0.60 ``` ```r ## --- Classification --- iris.obj <- rfsrc(Species ~ ., data = iris, importance = TRUE) print(iris.obj$importance) # Petal.Length Petal.Width Sepal.Length Sepal.Width # ... ... ... ... ``` ```r ## --- Survival --- data(veteran, package = "randomForestSRC") v.obj <- rfsrc(Surv(time, status) ~ ., data = veteran, block.size = 1) print(v.obj) # OOB C-error (Uno-IPCW): ~0.36 ``` ```r ## --- Competing Risks --- data(wihs, package = "randomForestSRC") wihs.obj <- rfsrc(Surv(time, status) ~ ., wihs, nsplit = 3, ntree = 100) # Returns cif.oob: [n x time x event] array of cumulative incidence functions ``` ```r ## --- Multivariate Mixed Outcomes --- data(nutrigenomic, package = "randomForestSRC") uevo <- data.frame(diet = nutrigenomic$diet, genotype = nutrigenomic$genotype, nutrigenomic$lipids) mv.obj <- rfsrc(get.mv.formula(colnames(ydta)), data.frame(ydta, nutrigenomic$genes), importance = TRUE, nsplit = 10) print(get.mv.error(mv.obj)) # per-outcome error print(get.mv.vimp(mv.obj)) # per-outcome VIMP ``` ```r ## --- Unsupervised --- mtcars.unspv <- rfsrc(data = mtcars) # or equivalently: mtcars.unspv <- rfsrc(Unsupervised() ~ ., data = mtcars) ``` ```r ## --- Mahalanobis Splitting (correlated multivariate outcomes) --- if (requireNamespace("mlbench", quietly = TRUE)) { data(BostonHousing, package = "mlbench") bh.mreg <- rfsrc(Multivar(lstat, nox) ~ ., BostonHousing, importance = TRUE, splitrule = "mahal") print(get.mv.vimp(bh.mreg, standardize = TRUE)) } ``` ```r ## --- Fast Memory-Efficient Survival Forest --- data(pbc, package = "randomForestSRC") print(rfsrc(Surv(days, status) ~ ., pbc, ntree = 1000, nodesize = 1, splitrule = "random", save.memory = TRUE)) ``` -------------------------------- ### get.tree Source: https://context7.com/kogalur/randomforestsrc/llms.txt Extracts and visualizes a single tree from a trained random forest model. It supports various families and allows customization of terminal node displays. ```APIDOC ## `get.tree` — Extract and Visualize a Single Tree Extracts a single tree from a trained forest and renders it as an interactive visualization in the user's web browser (via the `data.tree` and `DiagrammeR` packages). Works for all families; terminal nodes show sample size and predicted values. ```r ## Survival tree with factor variables data(veteran, package = "randomForestSRC") vd <- veteran vd$celltype <- factor(vd$celltype) vd$diagtime <- factor(vd$diagtime) vd.obj <- rfsrc(Surv(time, status) ~ ., vd, ntree = 100, nodesize = 5) plot(get.tree(vd.obj, 3)) ## Classification: class probability displayed in terminal nodes iris.obj <- rfsrc(Species ~ ., data = iris, nodesize = 10) plot(get.tree(iris.obj, 25, class.type = "prob", target = "setosa")) plot(get.tree(iris.obj, 25, class.type = "bayes")) ## Regression tree airq.obj <- rfsrc(Ozone ~ ., data = airquality) plot(get.tree(airq.obj, 10)) ## Multivariate mixed outcomes mtcars2 <- mtcars mtcars2$carb <- factor(mtcars2$carb) mtcars2$cyl <- factor(mtcars2$cyl) mtcars.mix <- rfsrc(Multivar(carb, mpg, cyl) ~ ., data = mtcars2) plot(get.tree(mtcars.mix, 5, m.target = "cyl")) ## Imbalanced data: compare RFQ vs Bayes rule in the same tree partition data(breast, package = "randomForestSRC") breast.obj <- imbalanced(status ~ ., na.omit(breast)) plot(get.tree(breast.obj, 1, class.type = "rfq", ensemble = TRUE)) plot(get.tree(breast.obj, 1, class.type = "bayes", ensemble = TRUE)) ``` ``` -------------------------------- ### rfsrc — Grow a Random Forest Source: https://context7.com/kogalur/randomforestsrc/llms.txt The main entry point for fitting any random forest. The family (regression, classification, survival, competing risks, multivariate, unsupervised, quantile) is inferred automatically from the formula and data. Supports OpenMP parallel execution, multiple splitting rules, bootstrap strategies, and optional variable importance computation at training time. ```APIDOC ## rfsrc — Grow a Random Forest ### Description The main entry point for fitting any random forest. The family (regression, classification, survival, competing risks, multivariate, unsupervised, quantile) is inferred automatically from the formula and data. Supports OpenMP parallel execution, multiple splitting rules, bootstrap strategies, and optional variable importance computation at training time. ### Usage ```r library(randomForestSRC) ## --- Regression --- airq.obj <- rfsrc(Ozone ~ ., data = airquality, na.action = "na.impute") print(airq.obj) ## --- Classification --- iris.obj <- rfsrc(Species ~ ., data = iris, importance = TRUE) print(iris.obj$importance) ## --- Survival --- data(veteran, package = "randomForestSRC") v.obj <- rfsrc(Surv(time, status) ~ ., data = veteran, block.size = 1) print(v.obj) ## --- Competing Risks --- data(wihs, package = "randomForestSRC") wihs.obj <- rfsrc(Surv(time, status) ~ ., wihs, nsplit = 3, ntree = 100) ## --- Multivariate Mixed Outcomes --- data(nutrigenomic, package = "randomForestSRC") ydta <- data.frame(diet = nutrigenomic$diet, genotype = nutrigenomic$genotype, nutrigenomic$lipids) mv.obj <- rfsrc(get.mv.formula(colnames(ydta)), data.frame(ydta, nutrigenomic$genes), importance = TRUE, nsplit = 10) print(get.mv.error(mv.obj)) print(get.mv.vimp(mv.obj)) ## --- Unsupervised --- mtcars.unspv <- rfsrc(data = mtcars) mtcars.unspv <- rfsrc(Unsupervised() ~ ., data = mtcars) ## --- Mahalanobis Splitting (correlated multivariate outcomes) --- if (requireNamespace("mlbench", quietly = TRUE)) { data(BostonHousing, package = "mlbench") bh.mreg <- rfsrc(Multivar(lstat, nox) ~ ., BostonHousing, importance = TRUE, splitrule = "mahal") print(get.mv.vimp(bh.mreg, standardize = TRUE)) } ## --- Fast Memory-Efficient Survival Forest --- data(pbc, package = "randomForestSRC") print(rfsrc(Surv(days, status) ~ ., pbc, ntree = 1000, nodesize = 1, splitrule = "random", save.memory = TRUE)) ``` ``` -------------------------------- ### Balanced Random Forests (BRF) Source: https://context7.com/kogalur/randomforestsrc/llms.txt This code snippet shows how to train a balanced random forest model using the `imbalanced` function with the `method = "brf"` argument. The performance is then printed. ```r o.brf <- imbalanced(f, breast, method = "brf") print(get.imbalanced.performance(o.brf)) ``` -------------------------------- ### Train Predictive Imputer Source: https://context7.com/kogalur/randomforestsrc/llms.txt Trains a predictive imputer from labeled data for low-memory deployment. Supports missForest engine and custom sweep options. Requires the 'randomForestSRC' package. ```r set.seed(101) aq <- airquality[, c("Ozone", "Solar.R", "Wind", "Temp", "Month")] aq$Month <- factor(aq$Month) id <- sample(1:nrow(aq), 100) train <- aq[id, ] test <- aq[-id, ] ## Train the predictive imputer fit <- impute.learn( data = train, ntree = 25, mf.q = 1, # missForest engine max.iter = 5, full.sweep.options = list(ntree = 25, nsplit = 5) ) ``` -------------------------------- ### Train/test split with Variable Importance (VIMP) Source: https://context7.com/kogalur/randomforestsrc/llms.txt This snippet illustrates how to perform a train/test split for a random forest model and evaluate variable importance on both the training and testing sets. It prints the scaled importance values. ```r trn <- sample(1:nrow(breast), size = nrow(breast) / 2) o.trn <- imbalanced(f, breast[trn, ], importance = TRUE) o.tst <- predict(o.trn, breast[-trn, ], importance = TRUE) print(100 * cbind(o.trn$impo[, 1], o.tst$impo[, 1])) ``` -------------------------------- ### Fast Approximate Random Forest for Regression Source: https://context7.com/kogalur/randomforestsrc/llms.txt This snippet demonstrates using `rfsrc.fast` for regression on the housing dataset. It shows two calls with different `nodesize` parameters and prints the resulting model object. ```r data(housing, package = "randomForestSRC") housing <- impute(SalePrice ~ ., housing, ntree = 50, nimpute = 1, splitrule = "random") o1 <- rfsrc.fast(SalePrice ~ ., housing) o2 <- rfsrc.fast(SalePrice ~ ., housing, nodesize = 1) print(o1) ``` -------------------------------- ### Extract and Plot Imbalanced Data Tree (RFQ) Source: https://context7.com/kogalur/randomforestsrc/llms.txt Extracts and plots the 1st tree from an imbalanced random forest model trained on the breast dataset, using the RFQ classifier. Requires the randomForestSRC package. Ensemble mode is enabled. ```r data(breast, package = "randomForestSRC") breast.obj <- imbalanced(status ~ ., na.omit(breast)) plot(get.tree(breast.obj, 1, class.type = "rfq", ensemble = TRUE)) ``` -------------------------------- ### Train Predictive Imputer with OOD Scoring Source: https://context7.com/kogalur/randomforestsrc/llms.txt Trains a predictive imputer with out-of-distribution (OOD) scoring enabled, saving learners for every variable. Requires the 'randomForestSRC' package. ```r ## Train with OOD scoring enabled (target.mode = "all" recommended) ood.fit <- impute.learn( data = train, ntree = 25, mf.q = 1, max.iter = 5, target.mode = "all", # save learners for every variable save.ood = TRUE, full.sweep.options = list(ntree = 25, nsplit = 5), verbose = FALSE ) ``` -------------------------------- ### Hyperparameter Tuning for Competing Risks Source: https://context7.com/kogalur/randomforestsrc/llms.txt Tunes the 'nodesize' hyperparameter for a competing risks survival model using the wihs dataset. Requires 'randomForestSRC' package. ```R ## Competing risks (nodesize only) data(wihs, package = "randomForestSRC") plot(tune.nodesize(Surv(time, status) ~ ., wihs)$err, type = "s") ``` -------------------------------- ### Hyperparameter Tuning: Golden-Section Search Source: https://context7.com/kogalur/randomforestsrc/llms.txt Tunes hyperparameters for a random forest classification model on the wine dataset using a faster, noise-tolerant golden-section search. Requires 'randomForestSRC' package. ```R ## Golden-section search (faster, noise-tolerant) o2 <- tune(quality ~ ., wine, sampsize = 100, method = "golden", reps.initial = 2, reps.final = 3, seed = 1) print(o2$optimal) ``` -------------------------------- ### Extract and Plot Classification Tree with Class Probabilities Source: https://context7.com/kogalur/randomforestsrc/llms.txt Extracts and plots the 25th tree from a classification random forest model trained on the iris dataset. Displays class probabilities in terminal nodes. Requires the randomForestSRC package. ```r iris.obj <- rfsrc(Species ~ ., data = iris, nodesize = 10) plot(get.tree(iris.obj, 25, class.type = "prob", target = "setosa")) ``` -------------------------------- ### Double Bootstrap for Random Forest Source: https://context7.com/kogalur/randomforestsrc/llms.txt Performs a double bootstrap on a random forest object for potentially more accurate results, though it is slower. Requires the 'randomForestSRC' package. ```r reg.dbs.o <- subsample(reg.o, B = 25, bootstrap = TRUE) plot(reg.dbs.o) ``` -------------------------------- ### subsample — VIMP Confidence Intervals via Subsampling Source: https://context7.com/kogalur/randomforestsrc/llms.txt Constructs standard errors and confidence intervals for variable importance using subsampling. Also computes uncertainty for the generalization (OOB) error when `performance = TRUE`. Supports joint VIMP intervals, stratified subsampling for classification/survival, and an optional double-bootstrap mode. ```APIDOC ## `subsample` — VIMP Confidence Intervals via Subsampling Constructs standard errors and confidence intervals for variable importance using subsampling (Ishwaran & Lu, 2019). Also computes uncertainty for the generalization (OOB) error when `performance = TRUE`. Supports joint VIMP intervals, stratified subsampling for classification/survival, and an optional double-bootstrap mode. ```r ## Regression reg.o <- rfsrc(Ozone ~ ., airquality) reg.smp.o <- subsample(reg.o) plot(reg.smp.o) # confidence interval plot print(reg.smp.o) ## Joint VIMP CI + generalization error CI reg.smp.o2 <- subsample(reg.o, performance = TRUE, joint = TRUE, xvar.names = c("Day", "Month")) plot(reg.smp.o2) ## Generalization error uncertainty only gerror <- subsample(reg.o, performance.only = TRUE) plot(gerror) ## Survival data(pbc, package = "randomForestSRC") srv.o <- rfsrc(Surv(days, status) ~ ., pbc) srv.smp.o <- subsample(srv.o, B = 100) plot(srv.smp.o) ## Competing risks (target event = 2) if (requireNamespace("survival", quietly = TRUE)) { data(pbc, package = "survival") pbc$id <- NULL cr.o <- rfsrc(Surv(time, status) ~ ., pbc, splitrule = "logrankCR", cause = 2) cr.smp.o <- subsample(cr.o, B = 100) plot(cr.smp.o, target = 2) } ``` ``` -------------------------------- ### Fast Approximate Random Forest for Survival Analysis Source: https://context7.com/kogalur/randomforestsrc/llms.txt This code demonstrates using `rfsrc.fast` for survival analysis, comparing logrank and random splitting rules using the Brier score. It plots the Brier scores for both methods. ```r data(peakVO2, package = "randomForestSRC") f <- as.formula(Surv(ttodead, died) ~ .) o1 <- rfsrc.fast(f, peakVO2, perf.type = "none") o2 <- rfsrc.fast(f, peakVO2, perf.type = "none", splitrule = "random") bs1 <- get.brier.survival(o1, cens.model = "km") bs2 <- get.brier.survival(o2, cens.model = "km") plot(bs2$brier.score, type = "s", col = 2) lines(bs1$brier.score, type = "s", col = 4) legend("bottomright", legend = c("random", "logrank"), fill = c(2, 4)) ``` -------------------------------- ### Extract and Plot Regression Tree Source: https://context7.com/kogalur/randomforestsrc/llms.txt Extracts and plots the 10th tree from a regression random forest model trained on the airquality dataset. Requires the randomForestSRC package. ```r airq.obj <- rfsrc(Ozone ~ ., data = airquality) plot(get.tree(airq.obj, 10)) ``` -------------------------------- ### Impute New Data with Predictive Imputer Source: https://context7.com/kogalur/randomforestsrc/llms.txt Applies a trained predictive imputer to new data for imputation. Allows control over prediction iterations and verbosity. Requires the 'randomForestSRC' package. ```r ## Impute new data test.imp <- predict(fit, test, max.predict.iter = 2, verbose = FALSE) head(test.imp) ``` -------------------------------- ### Fast SID Clustering for Large Data Source: https://context7.com/kogalur/randomforestsrc/llms.txt Performs fast SID clustering on the mtcars dataset with k=4 and prints the resulting cluster assignments. ```r o.fast <- sidClustering(mtcars, k = 4, fast = TRUE) print(o.fast$cl) ``` -------------------------------- ### Standard Quantile Regression Source: https://context7.com/kogalur/randomforestsrc/llms.txt Performs standard quantile regression on the mtcars dataset and prints quantile estimates and statistics. Requires the 'randomForestSRC' package. ```R ## Standard quantile regression o <- quantreg(mpg ~ ., mtcars) print(get.quantile(o, c(0.25, 0.50, 0.75))) print(get.quantile.stat(o)) # conditional mean and std deviation plot(get.quantile.crps(o), type = "l") # CRPS over training values ``` -------------------------------- ### Spike-Sensitive Aggregation for OOD Scoring Source: https://context7.com/kogalur/randomforestsrc/llms.txt Applies spike-sensitive aggregation (L_p norm) to OOD scores for anomaly detection. Requires the 'randomForestSRC' package. ```r ## Spike-sensitive aggregation (L_p norm with p=4) ood.lp <- impute.ood(ood.fit, test, aggregate = "weighted.lp", aggregate.args = list(p = 4), verbose = FALSE) head(ood.lp$score.percentile) ``` -------------------------------- ### impute.learn / predict.impute.learn / impute.ood Source: https://context7.com/kogalur/randomforestsrc/llms.txt Trains a predictive imputer from labeled data that can be saved to disk and reloaded for compact, low-memory deployment. Supports out-of-distribution scoring at test time via `impute.ood`, returning row-level anomaly scores. ```APIDOC ## impute.learn / predict.impute.learn / impute.ood — Deployment Imputer with OOD Scoring Trains a predictive imputer from labeled data that can be saved to disk and reloaded for compact, low-memory deployment. Unlike `impute`, this stores per-variable random forest learners and applies them iteratively to new data. When `save.ood = TRUE`, the imputer also supports out-of-distribution scoring at test time via `impute.ood`, returning row-level anomaly scores calibrated against out-of-bag training reconstruction errors. ```r set.seed(101) aq <- airquality[, c("Ozone", "Solar.R", "Wind", "Temp", "Month")] aq$Month <- factor(aq$Month) id <- sample(1:nrow(aq), 100) train <- aq[id, ] test <- aq[-id, ] ## Train the predictive imputer fit <- impute.learn( data = train, ntree = 25, mf.q = 1, # missForest engine max.iter = 5, full.sweep.options = list(ntree = 25, nsplit = 5) ) ## Impute new data test.imp <- predict(fit, test, max.predict.iter = 2, verbose = FALSE) head(test.imp) ## Train with OOD scoring enabled (target.mode = "all" recommended) ood.fit <- impute.learn( data = train, ntree = 25, mf.q = 1, max.iter = 5, target.mode = "all", # save learners for every variable save.ood = TRUE, full.sweep.options = list(ntree = 25, nsplit = 5), verbose = FALSE ) ## Score test data for out-of-distribution behavior ood <- impute.ood(ood.fit, test, return.details = TRUE, verbose = FALSE) head(ood$score) # row-level OOD score (larger = more anomalous) head(ood$score.percentile) # percentile relative to training OOB reference ## Spike-sensitive aggregation (L_p norm with p=4) ood.lp <- impute.ood(ood.fit, test, aggregate = "weighted.lp", aggregate.args = list(p = 4), verbose = FALSE) head(ood.lp$score.percentile) ## Save and reload the imputer (requires fst package) ## bundle.dir <- file.path(tempdir(), "my.imputer") ## save.impute.learn(fit, bundle.dir) ## imp <- load.impute.learn(bundle.dir, lazy = TRUE) ## test.imp2 <- predict(imp, test) ``` ``` -------------------------------- ### SID Clustering of mtcars Data Source: https://context7.com/kogalur/randomforestsrc/llms.txt Performs default SID clustering on the mtcars dataset and prints the split data for 3-cluster and 10-cluster solutions. ```r o1 <- sidClustering(mtcars, k = 1:10) print(split(mtcars, o1$cl[, 3])) # 3-cluster solution print(split(mtcars, o1$cl[, 10])) # 10-cluster solution ``` -------------------------------- ### Extract and Plot Imbalanced Data Tree (Bayes) Source: https://context7.com/kogalur/randomforestsrc/llms.txt Extracts and plots the 1st tree from an imbalanced random forest model trained on the breast dataset, using the Bayes rule classifier. Requires the randomForestSRC package. Ensemble mode is enabled. ```r data(breast, package = "randomForestSRC") breast.obj <- imbalanced(status ~ ., na.omit(breast)) plot(get.tree(breast.obj, 1, class.type = "bayes", ensemble = TRUE)) ``` -------------------------------- ### Holdout VIMP for Multivariate Regression Source: https://context7.com/kogalur/randomforestsrc/llms.txt Calculates holdout Variable Importance (VIMP) for a multivariate regression problem. Demonstrates parameters like `vtry`, `block.size`, and `samptype`. ```r mtcars.mreg <- holdout.vimp(Multivar(mpg, cyl) ~ ., data = mtcars, vtry = 3, block.size = 1, samptype = "swr", sampsize = nrow(mtcars)) print(mtcars.mreg$importance) ``` -------------------------------- ### impute Source: https://context7.com/kogalur/randomforestsrc/llms.txt Grows a forest solely for the purpose of imputing missing values. Supports unsupervised, outcome-guided, and missForest-style algorithms, as well as an optional final full-sweep pass for improved self-consistency. ```APIDOC ## impute — Fast Random Forest Imputation Grows a forest solely for the purpose of imputing missing values. No ensemble statistics or error rates are calculated, making this the fastest route to a complete dataset. Supports unsupervised, outcome-guided, and missForest-style algorithms, as well as an optional final full-sweep pass (`full.sweep = TRUE`) for improved self-consistency. ```r ## Unsupervised imputation (default) data(pbc, package = "randomForestSRC") pbc1.d <- impute(data = pbc) ## Outcome-guided imputation f <- as.formula(Surv(days, status) ~ .) pbc2.d <- impute(f, data = pbc, nsplit = 3) ## Fast random splitting (good accuracy, much faster) pbc3.d <- impute(f, data = pbc, splitrule = "random", nimpute = 5) ## missForest algorithm (1 variable at a time as response) pbc.mf <- impute(data = pbc, mf.q = 1) ## Multivariate missForest (10% of variables as responses per round) pbc.mv <- impute(data = pbc, mf.q = 0.10) ## Optional final sweep for regression data with custom sweep options air.fs <- impute(Ozone ~ ., data = airquality, nimpute = 5, full.sweep = TRUE, full.sweep.options = list(ntree = 1000, nodesize = 5, nsplit = 0, mtry = 3)) ## Fast imputation of large data (uses rfsrc.fast internally) data(housing, package = "randomForestSRC") housing.imp <- impute(data = housing, fast = TRUE) ``` ``` -------------------------------- ### Holdout VIMP for Survival Analysis Source: https://context7.com/kogalur/randomforestsrc/llms.txt Applies the holdout Variable Importance (VIMP) method to survival analysis data. Includes parameters for number of splits, trees, and imputation of missing values. ```r data(pbc, package = "randomForestSRC") pbc.obj <- holdout.vimp(Surv(days, status) ~ ., pbc, nsplit = 10, ntree = 1000, na.action = "na.impute") print(pbc.obj$importance) ``` -------------------------------- ### Survival VIMP with Different Block Sizes Source: https://context7.com/kogalur/randomforestsrc/llms.txt Calculates survival Variable Importance (VIMP) with different block sizes. Demonstrates tree-averaged VIMP and permutation VIMP for survival objects. ```r data(pbc, package = "randomForestSRC") pbc.obj <- rfsrc(Surv(days, status) ~ ., pbc) print(vimp(pbc.obj, block.size = 1)$importance) # tree-averaged print(vimp(pbc.obj, importance = "permute")$importance) # permutation ``` -------------------------------- ### Joint VIMP CI and Generalization Error CI via Subsampling Source: https://context7.com/kogalur/randomforestsrc/llms.txt Computes joint Variable Importance (VIMP) confidence intervals and generalization error confidence intervals using subsampling. Includes plotting functionality. ```r reg.o <- rfsrc(Ozone ~ ., airquality) reg.smp.o2 <- subsample(reg.o, performance = TRUE, joint = TRUE, xvar.names = c("Day", "Month")) plot(reg.smp.o2) ``` -------------------------------- ### Default RFQ call for imbalanced data Source: https://context7.com/kogalur/randomforestsrc/llms.txt This snippet demonstrates the default Random Forest Quantile (RFQ) call for imbalanced datasets using the `imbalanced` function. It prints the performance metrics obtained from the imbalanced object. ```r o.rfq <- imbalanced(f, breast) print(get.imbalanced.performance(o.rfq)) ``` -------------------------------- ### Subsample for Regression VIMP Confidence Intervals Source: https://context7.com/kogalur/randomforestsrc/llms.txt Constructs standard errors and confidence intervals for Variable Importance (VIMP) in regression using subsampling. Also plots the confidence intervals. ```r reg.o <- rfsrc(Ozone ~ ., airquality) reg.smp.o <- subsample(reg.o) plot(reg.smp.o) # confidence interval plot print(reg.smp.o) ``` -------------------------------- ### Partial Effect on Mortality (Survival) Source: https://context7.com/kogalur/randomforestsrc/llms.txt Calculates and plots the partial effect of 'age' on mortality using the veteran dataset for a survival model. Requires the 'randomForestSRC' package. ```R data(veteran, package = "randomForestSRC") v.obj <- rfsrc(Surv(time, status) ~ ., veteran, nsplit = 10, ntree = 100) partial.obj <- partial(v.obj, partial.type = "mort", partial.xvar = "age", partial.values = v.obj$xvar$age, partial.time = v.obj$time.interest) pdta <- get.partial.plot.data(partial.obj) plot(lowess(pdta$x, pdta$yhat, f = 1/3), type = "l", xlab = "Age", ylab = "Adjusted Mortality") ``` -------------------------------- ### Extract and Plot Classification Tree with Bayes Rule Source: https://context7.com/kogalur/randomforestsrc/llms.txt Extracts and plots the 25th tree from a classification random forest model trained on the iris dataset. Displays Bayes rule in terminal nodes. Requires the randomForestSRC package. ```r iris.obj <- rfsrc(Species ~ ., data = iris, nodesize = 10) plot(get.tree(iris.obj, 25, class.type = "bayes")) ``` -------------------------------- ### Calculate Anti VIMP (Default) Source: https://context7.com/kogalur/randomforestsrc/llms.txt Computes the default anti-split Variable Importance (VIMP) for a random forest model. This is a fast method for assessing variable importance. ```r iris.obj <- rfsrc(Species ~ ., data = iris) print(vimp(iris.obj)$importance) ``` -------------------------------- ### Subsampling for Competing Risks VIMP Confidence Intervals Source: https://context7.com/kogalur/randomforestsrc/llms.txt Calculates Variable Importance (VIMP) confidence intervals for competing risks survival analysis using subsampling. Requires the 'survival' package and specifies the target event. ```r if (requireNamespace("survival", quietly = TRUE)) { data(pbc, package = "survival") pbc$id <- NULL cr.o <- rfsrc(Surv(time, status) ~ ., pbc, splitrule = "logrankCR", cause = 2) cr.smp.o <- subsample(cr.o, B = 100) plot(cr.smp.o, target = 2) } ``` -------------------------------- ### Predict with Missing Values Imputation Source: https://context7.com/kogalur/randomforestsrc/llms.txt Demonstrates prediction on test data containing missing values, using the 'na.impute' action to handle them. Requires the 'randomForestSRC' package. ```r data(pbc, package = "randomForestSRC") o <- rfsrc(Surv(days, status) ~ ., pbc[1:312, ]) print(predict(o, pbc[-(1:312), ], na.action = "na.impute")) ``` -------------------------------- ### missForest Algorithm Imputation Source: https://context7.com/kogalur/randomforestsrc/llms.txt Imputes missing values using the missForest algorithm, processing one variable at a time as the response. Requires the 'randomForestSRC' package. ```r pbc.mf <- impute(data = pbc, mf.q = 1) ``` -------------------------------- ### Extract and Plot Survival Tree Source: https://context7.com/kogalur/randomforestsrc/llms.txt Extracts and plots the 3rd tree from a survival random forest model trained on the veteran dataset. Requires the randomForestSRC package. The veteran dataset is loaded from the package. ```r data(veteran, package = "randomForestSRC") vd <- veteran vd$celltype <- factor(vd$celltype) vd$diagtime <- factor(vd$diagtime) vd.obj <- rfsrc(Surv(time, status) ~ ., vd, ntree = 100, nodesize = 5) plot(get.tree(vd.obj, 3)) ``` -------------------------------- ### Fast Random Splitting Imputation Source: https://context7.com/kogalur/randomforestsrc/llms.txt Imputes missing values using a fast random splitting strategy for improved accuracy and speed. Requires the 'randomForestSRC' package. ```r f <- as.formula(Surv(days, status) ~ .) pbc3.d <- impute(f, data = pbc, splitrule = "random", nimpute = 5) ``` -------------------------------- ### Calculate Permutation VIMP Source: https://context7.com/kogalur/randomforestsrc/llms.txt Computes Variable Importance (VIMP) using the permutation method (Breiman-Cutler). This method is more conservative than the default anti-split method. ```r iris.obj <- rfsrc(Species ~ ., data = iris) print(vimp(iris.obj, importance = "permute")$importance) ``` -------------------------------- ### Fast Imputation of Large Datasets Source: https://context7.com/kogalur/randomforestsrc/llms.txt Efficiently imputes missing values in large datasets by utilizing the 'rfsrc.fast' internal function. Requires the 'randomForestSRC' package. ```r data(housing, package = "randomForestSRC") housing.imp <- impute(data = housing, fast = TRUE) ``` -------------------------------- ### Score Test Data for Out-of-Distribution Behavior Source: https://context7.com/kogalur/randomforestsrc/llms.txt Scores test data for out-of-distribution behavior using a trained imputer, returning row-level anomaly scores and their percentiles relative to training data. Requires the 'randomForestSRC' package. ```r ## Score test data for out-of-distribution behavior ood <- impute.ood(ood.fit, test, return.details = TRUE, verbose = FALSE) head(ood$score) # row-level OOD score (larger = more anomalous) head(ood$score.percentile) # percentile relative to training OOB reference ``` -------------------------------- ### vimp — Variable Importance Source: https://context7.com/kogalur/randomforestsrc/llms.txt Computes Variable Importance (VIMP) for a single variable, a set of variables, or jointly for a group of variables from a previously trained forest. Supports anti-split, permutation, and Brier-score-based methods, as well as case-specific and joint VIMP. ```APIDOC ## `vimp` — Variable Importance Computes VIMP for a single variable, a set of variables, or jointly for a group of variables from a previously trained forest. Three methods are available: anti-split (default, fast), permutation (Breiman-Cutler, more conservative), and random daughter assignment. Supports case-specific VIMP and joint VIMP. ```r iris.obj <- rfsrc(Species ~ ., data = iris) ## Anti VIMP (default) print(vimp(iris.obj)$importance) ## Permutation VIMP print(vimp(iris.obj, importance = "permute")$importance) ## Brier-score-based VIMP print(vimp(iris.obj, perf.type = "brier")$importance) ## Joint VIMP for a pair of variables print(vimp(iris.obj, c("Petal.Length", "Petal.Width"), joint = TRUE)$importance) ## Survival VIMP with different block sizes data(pbc, package = "randomForestSRC") pbc.obj <- rfsrc(Surv(days, status) ~ ., pbc) print(vimp(pbc.obj, block.size = 1)$importance) # tree-averaged print(vimp(pbc.obj, importance = "permute")$importance) # permutation ## VIMP computed on test data set.seed(100080) train <- sample(1:nrow(airquality), size = 80) airq.obj <- rfsrc(Ozone ~ ., airquality[train, ]) print(vimp(airq.obj, newdata = airquality[-train, ])$importance) ## Case-specific VIMP for multivariate regression o <- rfsrc(Multivar(mpg, cyl) ~ ., data = mtcars) v <- vimp(o, joint = TRUE, csv = TRUE) print(get.mv.csvimp(v, standardize = TRUE)) ``` ``` -------------------------------- ### Subsample for Survival VIMP Confidence Intervals Source: https://context7.com/kogalur/randomforestsrc/llms.txt Constructs standard errors and confidence intervals for Variable Importance (VIMP) in survival analysis using subsampling. Plots the resulting confidence intervals. ```r data(pbc, package = "randomForestSRC") srv.o <- rfsrc(Surv(days, status) ~ ., pbc) srv.smp.o <- subsample(srv.o, B = 100) plot(srv.smp.o) ```