### Install robustlmm from GitHub Source: https://cran.r-project.org/web/packages/robustlmm/readme/README.html Install the robustlmm package from GitHub using the devtools package. This method requires devtools to be installed first and then loads the package. ```r install.packages("devtools") ## if not already installed require(devtools) install_github("kollerma/robustlmm") require(robustlmm) ``` -------------------------------- ### Generate ANOVA Datasets Example Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Demonstrates generating datasets for ANOVA models and accessing generated data components. ```R oneWay <- generateAnovaDatasets(2, 1, 5, 4) head(oneWay$generateData(1)) head(oneWay$generateData(2)) oneWay$formula head(oneWay$randomEffects(1)) head(oneWay$sphericalRandomEffects(1)) head(oneWay$errors(1)) ``` ```R twoWayFixedRandom <- generateAnovaDatasets(2, 3, 5, 4) head(twoWayFixedRandom$generateData(1)) twoWayFixedRandom$formula ``` ```R twoWayRandom <- generateAnovaDatasets(2, 1, c(3, 5), 4) head(twoWayRandom$generateData(1)) twoWayRandom$formula ``` ```R large <- generateAnovaDatasets(2, c(10, 15), c(20, 30), 5) head(large$generateData(1)) large$formula ``` ```R set.seed(1) datasets1 <- generateAnovaDatasets(2, 1, 5, 4) set.seed(1) datasets2 <- generateAnovaDatasets(3, 1, 5, 4) stopifnot(all.equal(datasets1$generateData(1), datasets2$generateData(1)), all.equal(datasets1$generateData(2), datasets2$generateData(2))) ``` -------------------------------- ### Install Robustlmm Package with Full Results Source: https://cran.r-project.org/web/packages/robustlmm/vignettes/simulationStudies.Rnw Installs the 'robustlmm' package from GitHub, including the full simulation results, which are not available in the CRAN version due to size constraints. Use this to ensure complete data for replication. ```r remotes::install_github("kollerma/robustlmm", "full-results") ``` -------------------------------- ### Initialize R options and load package Source: https://cran.r-project.org/web/packages/robustlmm/vignettes/rlmer.R Sets R options for output formatting and loads the robustlmm package. It also prints warnings about package directory contents and the location of the example data file. ```R options(width = 60, str = strOptions(vec.len = 1.4), prompt = 'R> ', continue = '+ ') require("robustlmm") warning("Current dir: ", system.file("", package = "robustlmm"), " has contents: ", paste(list.files(system.file("", package = "robustlmm")), collapse = ", ")) warning("doc dir: ", system.file("doc", package = "robustlmm"), " has contents: ", paste(list.files(system.file("doc", package = "robustlmm")), collapse = ", ")) filename <- system.file("doc/Penicillin.R", package = "robustlmm", mustWork = TRUE) warning("Filename: ", filename) source(filename) ``` -------------------------------- ### Initialize Robust Model from lmer Fit Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Demonstrates how to initialize a robust mixed-effects model fit using the results from a standard lmer fit, rather than starting from scratch. ```R rlmer(Yield ~ (1|Batch), Dyestuff, init = lmerNoFit) ``` -------------------------------- ### Install robustlmm from CRAN Source: https://cran.r-project.org/web/packages/robustlmm/readme/README.html Install the robustlmm package directly from CRAN using this command in R. Ensure lme4 and other dependencies are met. ```r install.packages("robustlmm") ``` -------------------------------- ### Compare Weighted and Unweighted Residuals Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Compares weighted and unweighted residuals from a fitted rlmer model. This example demonstrates how to access and compare different types of residuals, using 'response' and 'weighted' types. ```R ## Not run: fm <- rlmer(Yield ~ (1|Batch), Dyestuff) stopifnot(all.equal(resid(fm, type="weighted"), resid(fm) * getME(fm, "w_e"))) ## End(Not run) ``` -------------------------------- ### List available methods for rlmerMod objects Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Lists all available methods for objects of class 'rlmerMod'. This is useful for understanding the full range of functionalities before using specific methods like getME. ```R methods(class = "rlmerMod") ``` -------------------------------- ### Extract components from a fitted rlmerMod object Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Demonstrates how to extract specific components (like the 'Z' matrix or 'beta' coefficients) from a fitted 'rlmerMod' object using the getME function. It also shows an internal consistency check by extracting all components. ```R (fm1 <- rlmer(Reaction ~ Days + (Days|Subject), sleepstudy, method="DASvar", doFit=FALSE)) Z <- getME(fm1, "Z") stopifnot(is(Z, "CsparseMatrix"), c(180,36) == dim(Z), all.equal(fixef(fm1), b1 <- getME(fm1, "beta"), check.attributes=FALSE, tolerance = 0)) ## A way to get *all* getME()s : ## internal consistency check ensuring that all work: parts <- getME(fm1, "ALL") str(parts, max=2) stopifnot(identical(Z, parts $ Z), identical(b1, parts $ beta)) stopifnot(all.equal(theta(fm1), getME(fm1, "theta"))) ``` -------------------------------- ### Convert lmerMod to rlmerMod and Compare Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Shows how to convert an existing 'lmerMod' object to an 'rlmerMod' object to utilize robustlmm methods. It then compares the results of the original and robust fits. ```R fm <- lmer(Yield ~ (1|Batch), Dyestuff) rfm <- as(fm, "rlmerMod") compare(fm, rfm) ``` -------------------------------- ### compare Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Compares the estimated parameters of multiple fits of lmerMod or rlmerMod objects. ```APIDOC ## Create comparison charts for multiple fits ### Description Use `compare` to quickly compare the estimated parameters of the fits of multiple lmerMod or rlmerMod objects. ### Usage ```R compare(..., digits = 3, dnames = NULL, show.rho.functions = TRUE) ## S3 method for class 'lmerMod' getInfo(object, ...) ## S3 method for class 'rlmerMod' getInfo(object, ...) ## S3 method for class 'comparison.table' xtable( x, caption = NULL, label = NULL, align = NULL, digits = NULL, display = NULL, ... ) ## S3 method for class 'xtable.comparison.table' print( x, add.hlines = TRUE, latexify.namescol = TRUE, include.rownames = FALSE, ... ) getInfo(object, ...) ``` ### Arguments `...` | objects to compare, or, for the `xtable` functions: passed to the respective `xtable` function. `digits` | number of digits to show in output `dnames` | names of objects given as arguments (optional) `show.rho.functions` | whether to show rho functions in output. `object` | object `x` | object of class "comparison.table" or "xtable.comparison.table" `caption` | see `xtable`. `label` | see `xtable`. `align` | see `xtable`. `display` | see `xtable`. `add.hlines` | replace empty lines in comparison table by hlines. Supersedes `hline.after` argument of `print.xtable`. `latexify.namescol` | replace “sigma” and “x” in the first column by latex equivalents. `include.rownames` | include row numbers (the object returned by `xtable.comparison.table` includes names in the first column) ``` -------------------------------- ### Create Dataset List for Model Fitting Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Generates a list of datasets from input data objects, suitable for use with `processFit` and `fitDatasets` functions. Requires `lmer` from `lme4` and `getME` for extracting model parameters. ```R data(sleepstudy) sleepstudy2 <- sleepstudy sleepstudy2[1, "Reaction"] <- sleepstudy2[1, "Reaction"] + 10 fm1 <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy) datasets <- createDatasetsFromList(list(sleepstudy, sleepstudy2), formula = Reaction ~ Days + (Days|Subject), trueBeta = getME(fm1, "beta"), trueSigma = sigma(fm1), trueTheta = getME(fm1, "theta")) fitDatasets_lmer(datasets) ``` -------------------------------- ### prepareMixedEffectDataset Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Prepares a dataset for parametric bootstrap by fitting a linear mixed-effects model using lmer and extracting necessary components. ```APIDOC ## prepareMixedEffectDataset ### Description This function runs `lmer` and extracts all information needed to generate new datasets using parametric bootstrap later. ### Usage ```R prepareMixedEffectDataset( formula, data, REML = TRUE, overrideBeta, overrideSigma, overrideTheta, ... ) ``` ### Arguments - **formula** - passed on to `lmer` - **data** - passed on to `lmer` - **REML** (logical) - passed on to `lmer`. Default: `TRUE`. - **overrideBeta** - use to override beta used to simulate new datasets, by default `getME``(fm, "beta")` where `fm` is the fitted model returned by `lmer`. - **overrideSigma** - use to override sigma used to simulate new datasets, by default `getME``(fm, "sigma")` where `fm` is the fitted model returned by `lmer`. - **overrideTheta** - use to override theta used to simulate new datasets, by default `getME``(fm, "theta")` where `fm` is the fitted model returned by `lmer`. - **...** - all additional arguments are added to the returned list. ### Value List that can be passed to `generateMixedEffectDatasets`. - **data** (data.frame) - the original dataset - **X** (matrix) - the X matrix as returned by `getME` - **Z** (matrix) - the Z matrix as returned by `getME` - **Lambda** (matrix) - the Lambda matrix as returned by `getME` - **numberOfFixedEffects** (integer) - the number of fixed effects coefficients - **numberOfRandomEffects** (integer) - the number of random effects - **numberOfRows** (integer) - number of rows in the generated dataset - **trueBeta** (numeric) - true values used for beta - **trueSigma** (numeric) - true value used for sigma - **trueTheta** (numeric) - true values used for theta - **formula** (formula) - formula to fit the model using `lmer` - **...** - additional arguments passed via `...` ### Author(s) Manuel Koller ### Examples ```R preparedDataset <- prepareMixedEffectDataset(Reaction ~ Days + (Days|Subject), sleepstudy) str(preparedDataset) ``` ``` -------------------------------- ### Prepare and Analyze Difference Data Source: https://cran.r-project.org/web/packages/robustlmm/vignettes/rlmer.R Creates a data frame from the computed metrics, calculates the difference between realized and expected values, and prepares data for plotting. ```R test.1 <- data.frame(t(ssq[1:3,])) colnames(test.1) <- c("theta", "realized", "expected") test.1$difference <- test.1$realized - test.1$expected ``` -------------------------------- ### Fit Robust Mixed-Effects Models with Different Methods Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Demonstrates fitting a robust mixed-effects model using the DASvar method and compares it with the default DAStau method. The DASvar method is faster but less accurate. ```R system.time(print(rlmer(Yield ~ (1|Batch), Dyestuff2, method="DASvar"))) ``` ```R ## Default method "DAStau" system.time(rfm.DAStau <- rlmer(Yield ~ (1|Batch), Dyestuff)) summary(rfm.DAStau) ## DASvar method (faster, less accurate) system.time(rfm.DASvar <- rlmer(Yield ~ (1|Batch), Dyestuff, method="DASvar")) ## compare the two compare(rfm.DAStau, rfm.DASvar) ``` -------------------------------- ### PsiFunction Class Methods (show) Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Provides the S4 method for displaying instances of the PsiFunction class and its subclasses, including Rcpp_SmoothPsi, Rcpp_HuberPsi, and wrappers. ```APIDOC ## Other methods ### Description Other miscellaneous utilities for instances of the PsiFunction class. ### Usage ```R ## S4 method for signature 'Rcpp_SmoothPsi' show(object) ## S4 method for signature 'Rcpp_HuberPsi' show(object) ## S4 method for signature 'Rcpp_PsiFunction' show(object) ## S4 method for signature 'Rcpp_PsiFunctionToPropIIPsiFunctionWrapper' show(object) ``` ### Arguments `object` | instance of class `PsiFunction` to be plotted ---|--- ### Examples ```R show(smoothPsi) ``` ``` -------------------------------- ### Generate Datasets for Sensitivity Curves Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Creates datasets for sensitivity curve analysis by modifying observations. Allows specifying which observations to change, shifts, scales, and the centering point. ```R generateSensitivityCurveDatasets( data, observationsToChange, shifts, scales, center, formula, ... ) ``` -------------------------------- ### Prepare Dataset for Mixed-Effects Model Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Prepares a dataset for use with parametric bootstrap simulations by fitting a mixed-effects model using lmer. It extracts necessary components like design matrices and true parameter values. ```R preparedDataset <- prepareMixedEffectDataset(Reaction ~ Days + (Days|Subject), sleepstudy) str(preparedDataset) ``` -------------------------------- ### View Simulation Study Script in R Source: https://cran.r-project.org/web/packages/robustlmm/vignettes/simulationStudies.Rnw Opens a specified simulation study script in the R editor for viewing, editing, and running. This is useful for replicating study results. ```r robustlmm::viewCopyOfSimulationStudy("sensitivityCurves.R") ``` -------------------------------- ### Set R options for output width Source: https://cran.r-project.org/web/packages/robustlmm/vignettes/rlmer.R Temporarily sets the R output width option to 90 characters. The original options are stored in `oldopts` to be restored later. ```R oldopts <- options(width = 90) ``` -------------------------------- ### Compute and Print Metrics for Theta Values Source: https://cran.r-project.org/web/packages/robustlmm/vignettes/rlmer.R Generates a sequence of theta values, computes the metrics using the 'fun' function for each theta, and prints the head of the resulting matrix. ```R thetas <- exp(seq(0, log(4), length.out = 100)) - 1 ssq <- sapply(thetas, fun, rfm = rfm) print(head(t(ssq))) ``` -------------------------------- ### Fit and Compare Robust Mixed-Effects Models Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Demonstrates fitting a standard lmer model and a robust rlmer model, then comparing them. Requires the xtable package for output formatting. ```R fm1 <- lmer(Yield ~ (1|Batch), Dyestuff) fm2 <- rlmer(Yield ~ (1|Batch), Dyestuff) compare(fm1, fm2) require(xtable) xtable(compare(fm1, fm2)) str(getInfo(fm1)) ``` -------------------------------- ### getInfo Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Internally used function to prepare objects for producing a comparison chart in `compare`. It extracts estimated coefficients, variance components, and other fitting details. ```APIDOC ## getInfo ### Description The function `getInfo` is internally used to prepare object for producing a comparison chart in `compare`. ### Value `getInfo` returns a list with estimated coefficients, estimated variance components, sigma, deviance and parameter configuration used to fit. ### See Also `xtable` `print.xtable` ### Examples ```R ## Not run: fm1 <- lmer(Yield ~ (1|Batch), Dyestuff) fm2 <- rlmer(Yield ~ (1|Batch), Dyestuff) compare(fm1, fm2) require(xtable) xtable(compare(fm1, fm2)) str(getInfo(fm1)) ## End(Not run) ``` ``` -------------------------------- ### Generate Sensitivity Curve Datasets in R Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Generates datasets for sensitivity analysis by applying shifts to observations. Ensure 'shifts' or 'scales' are provided. The output can be used with 'processFit' and 'fitDatasets' functions. ```r oneWay <- generateAnovaDatasets(1, 1, 10, 5) datasets <- generateSensitivityCurveDatasets(oneWay$generateData(1), observationsToChange = 1:5, shifts = -10:10, formula = oneWay$formula) datasets$generateData(1) ``` -------------------------------- ### Generate and Split Datasets for ANOVA Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Generates datasets for ANOVA and splits them into chunks for processing. Verifies data generation and matrix creation consistency across chunks. ```R oneWay <- generateAnovaDatasets(18, 1, 5, 4) datasetList <- splitDatasets(oneWay, 5) data <- datasetList[[4]]$generateData(1) stopifnot(all.equal(oneWay$generateData(16), datasetList[[4]]$generateData(1), check.attributes = TRUE), all.equal(oneWay$sphericalRandomEffects(16), datasetList[[4]]$sphericalRandomEffects(1)), all.equal(oneWay$createXMatrix(data), datasetList[[4]]$createXMatrix(data)), all.equal(oneWay$createZMatrix(data), datasetList[[4]]$createZMatrix(data))) ``` -------------------------------- ### Fit Robust Models with Custom Robustness Functions Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Shows how to fit robust mixed-effects models using custom robustness functions like psi2propII and chgDefaults for variance component estimation. These settings are equivalent to using rlmer's 'setting' argument. ```R rlmer(diameter ~ 1 + (1|plate) + (1|sample), Penicillin, rho.sigma.e = psi2propII(smoothPsi, k = 2.28), rho.sigma.b = psi2propII(smoothPsi, k = 2.28)) ``` ```R rlmer(Reaction ~ Days + (Days|Subject), sleepstudy, rho.sigma.e = psi2propII(smoothPsi, k = 2.28), rho.b = chgDefaults(smoothPsi, k = 5.14, s=10), rho.sigma.b = chgDefaults(smoothPsi, k = 5.14, s=10)) ``` -------------------------------- ### Plotting Psi Functions Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Visualizes the rho, psi, Dpsi, and weight functions and their derivatives for various Psi function classes. ```APIDOC ## S4 method for signature 'Rcpp_SmoothPsi' plot(x, y, which = c("rho", "psi", "Dpsi", "wgt", "Dwgt"), main = "full", col = c("black", "red3", "blue3", "dark green", "light green"), leg.loc = "right", ...) ## S4 method for signature 'Rcpp_HuberPsi' plot(x, y, which = c("rho", "psi", "Dpsi", "wgt", "Dwgt"), main = "full", col = c("black", "red3", "blue3", "dark green", "light green"), leg.loc = "right", ...) ## S4 method for signature 'Rcpp_PsiFunction' plot(x, y, which = c("rho", "psi", "Dpsi", "wgt", "Dwgt"), main = "full", col = c("black", "red3", "blue3", "dark green", "light green"), leg.loc = "right", ...) ## S4 method for signature 'Rcpp_PsiFunctionToPropIIPsiFunctionWrapper' plot(x, y, which = c("rho", "psi", "Dpsi", "wgt", "Dwgt"), main = "full", col = c("black", "red3", "blue3", "dark green", "light green"), leg.loc = "right", ...) ### Arguments `x`: instance of class `PsiFunction` to be plotted `y`: (optional) vector of abscissa values (to plot object at). `which`: `character` vector of slots to be included in plot; by default, all of the slots are included `main`: string or logical indicating the kind of plot title; either `"full"`, `"short"` or `FALSE` which chooses a full, a short or no main title at all. `col`: colors to be used for the different slots `leg.loc`: legend placement, see also `x` argument of `legend` `...`: passed to `matplot` ### Note If you want to specify your own title, use `main=FALSE`, and a subsequent `title(...)` call. ### See Also `psi-functions`. ### Examples ```R plot(huberPsiRcpp) plot(huberPsiRcpp, which=c("psi", "Dpsi", "wgt"), main="short", leg = "topleft") plot(smoothPsi) ## Plotting aspect ratio = 1:1 : plot(smoothPsi, asp=1, main="short", which = c("psi", "Dpsi", "wgt", "Dwgt")) ``` ``` -------------------------------- ### Run Consistency and Efficiency Simulation (Block Diagonal) Source: https://cran.r-project.org/web/packages/robustlmm/vignettes/simulationStudies.Rnw Sources the R script that performs simulation studies for consistency and efficiency in the block diagonal case. This script is essential for generating the data used in the corresponding plots. ```r source(system.file("simulationStudy/consistencyAndEfficiencyBlockDiagonal.R", package = "robustlmm")) ``` -------------------------------- ### Create Datasets From List in R Source: https://cran.r-project.org/web/packages/robustlmm/vignettes/simulationStudies.Rnw Converts a list of generated datasets into the required format for simulation studies in the robustlmm package. It offers flexibility but is less memory efficient than other generation functions. ```r createDatasetsFromList ``` -------------------------------- ### Find Tuning Parameter for Desired Efficiency Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Determines a tuning parameter for an M-estimator to achieve a specified asymptotic efficiency. Requires the desired efficiency, psi function, equation type, and dimension. An interval for the root search can also be provided. ```R findTuningParameter( desiredEfficiency, psi, equation = c("location", "scale", "eta", "tau", "mu"), dimension = 1, interval = c(0.15, 50), ... ) ``` -------------------------------- ### generateSensitivityCurveDatasets Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Creates a list of datasets that can be used to generate sensitivity curves. The response of the dataset is modified according to the supplied arguments, allowing for the exploration of model robustness. ```APIDOC ## Generate Datasets To Create Sensitivity Curves ### Description This method creates a list of datasets that can be used to create sensitivity curves. The response of the dataset is modified according to the supplied arguments. ### Usage ```R generateSensitivityCurveDatasets( data, observationsToChange, shifts, scales, center, formula, ... ) ``` ### Arguments `data` | dataset to be modified. `observationsToChange` | index or logical vector indicating which observations should be modified. `shifts` | vector of shifts that should be applied one by one to each of the modified observations. `scales` | vector scales that should be used to scale the observations around their original center. `center` | optional scalar used to define the center from which the observations are scaled from. If missing, the mean of all the changed observations is used. `formula` | formula to fit the model using `lmer`. `...` | all additional arguments are added to the returned list. ``` -------------------------------- ### Plot Psi Functions in robustlmm Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Visualizes rho, psi, Dpsi, and weight functions for robust estimation. Use to inspect the behavior of different psi functions. ```R plot(x, y, which = c("rho", "psi", "Dpsi", "wgt", "Dwgt"), main = "full", col = c("black", "red3", "blue3", "dark green", "light green"), leg.loc = "right", ...) ``` ```R plot(huberPsiRcpp) ``` ```R plot(huberPsiRcpp, which=c("psi", "Dpsi", "wgt"), main="short", leg = "topleft") ``` ```R plot(smoothPsi) ``` ```R plot(smoothPsi, asp=1, main="short", which = c("psi", "Dpsi", "wgt", "Dwgt")) ``` -------------------------------- ### getME Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Extracts generalized components from fitted mixed-effects models (objects of class 'rlmerMod' or 'merMod'). A comprehensive list of extractable components is available. ```APIDOC ## getME ### Description Extract (or “get”) “components” – in a generalized sense – from a fitted mixed-effects model, i.e. from an object of class `rlmerMod` or `merMod`. ### Usage ```R ## S3 method for class 'rlmerMod' getME( object, name = c("X", "Z", "Zt", "Ztlist", "mmList", "y", "mu", "u", "b.s", "b", "Gp", "Tp", "Lambda", "Lambdat", "Tlist", "A", "U_b", "Lind", "sigma", "flist", "fixef", "beta", "theta", "ST", "is_REML", "n_rtrms", "n_rfacs", "N", "n", "p", "q", "p_i", "l_i", "q_i", "k", "m_i", "m", "cnms", "devcomp", "offset", "lower", "rho_e", "rho_b", "rho_sigma_e", "rho_sigma_b", "M", "w_e", "w_b", "w_b_vector", "w_sigma_e", "w_sigma_b", "w_sigma_b_vector"), ... ) theta(object) ``` ### Arguments * `object`: A fitted mixed-effects model object (class `rlmerMod` or `merMod`). * `name`: The name of the component to extract. Defaults to a comprehensive list of available components. * `...`: Additional arguments. ### Details This function provides access to various internal components of fitted mixed-effects models, useful for advanced analysis and debugging. ``` -------------------------------- ### processFit Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Methods to process fitted objects and convert them into a data structure useful for post-processing. ```APIDOC ## processFit ### Description Methods to process fitted objects and convert into a data structure that is useful in post-processing. ### Usage ```R processFit( obj, all = FALSE, coefs = TRUE, stdErrors = all, tValues = all, sigma = TRUE, thetas = TRUE, b = all, meanB = all, meanAbsB = all, residuals = all, converged = TRUE, numWarnings = all, procTime = all, ... ) ## S3 method for class 'lmerMod' processFit( obj, all = FALSE, coefs = TRUE, stdErrors = all, tValues = all, sigma = TRUE, thetas = TRUE, b = all, meanB = all, meanAbsB = all, residuals = all, converged = TRUE, numWarnings = all, procTime = all, ... ) ``` ### Arguments - `obj` (object): The fitted model object. - `all` (logical): If TRUE, includes all available information. Defaults to FALSE. - `coefs` (logical): If TRUE, includes coefficients. Defaults to TRUE. - `stdErrors` (logical): If TRUE, includes standard errors. Defaults to `all`. - `tValues` (logical): If TRUE, includes t-values. Defaults to `all`. - `sigma` (logical): If TRUE, includes sigma. Defaults to TRUE. - `thetas` (logical): If TRUE, includes thetas. Defaults to TRUE. - `b` (logical): If TRUE, includes random effects (b). Defaults to `all`. - `meanB` (logical): If TRUE, includes the mean of random effects. Defaults to `all`. - `meanAbsB` (logical): If TRUE, includes the mean of the absolute values of random effects. Defaults to `all`. - `residuals` (logical): If TRUE, includes residuals. Defaults to `all`. - `converged` (logical): If TRUE, includes convergence status. Defaults to TRUE. - `numWarnings` (logical): If TRUE, includes the number of warnings. Defaults to `all`. - `procTime` (logical): If TRUE, includes processing time. Defaults to `all`. - `...`: Additional arguments. ``` -------------------------------- ### Extract Model Parameters and Calculate Metrics Source: https://cran.r-project.org/web/packages/robustlmm/vignettes/rlmer.R Extracts the estimated theta from the fitted model and calculates kappa. It then defines a function 'fun' to compute various metrics related to theta, realized, and expected values for further analysis. ```R true <- robustlmm:::theta(rfm) kappa <- robustlmm:::calcKappaTau(rfm@rho.sigma.b[[1]]) fun <- function(theta, rfm) { robustlmm:::theta(rfm) <- theta T <- diag(robustlmm:::len(rfm, "b")) - robustlmm:::rho.b(rfm)[[1]]@EDpsi() * (rfm@pp$L + t(rfm@pp$L)) + robustlmm:::rho.e(rfm)@Epsi2() * crossprod(rfm@pp$Kt) + robustlmm:::rho.b(rfm)[[1]]@Epsi2() * tcrossprod(rfm@pp$L) c(theta, mean(getME(rfm, "u")^2)/getME(rfm, "sigma")^2, mean(diag(T))*kappa ,mean(diag(robustlmm:::rho.b(rfm)[[1]]@EDpsi() * (rfm@pp$L + t(rfm@pp$L)))) ,mean(diag(robustlmm:::rho.e(rfm)@Epsi2() * crossprod(rfm@pp$Kt))) ,mean(diag(robustlmm:::rho.b(rfm)[[1]]@Epsi2() * tcrossprod(rfm@pp$L))) ,mean(diag(rfm@pp$D_b)) ) } ``` -------------------------------- ### Compute Asymptotic Efficiencies Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Functions to compute theoretical asymptotic efficiency and related tuning parameters for M-estimators. ```APIDOC ## Compute Asymptotic Efficiencies ### Description `asymptoticEfficiency` computes the theoretical asymptotic efficiency for an M-estimator for various types of equations. `asymptoticVariance` computes the asymptotic variance. `findTuningParameter` finds a tuning parameter for a desired asymptotic efficiency. ### Usage ```R asymptoticVariance( psi, equation = c("location", "scale", "eta", "tau", "mu"), dimension = 1 ) asymptoticEfficiency( psi, equation = c("location", "scale", "eta", "tau", "mu"), dimension = 1 ) findTuningParameter( desiredEfficiency, psi, equation = c("location", "scale", "eta", "tau", "mu"), dimension = 1, interval = c(0.15, 50), ... ) ``` ### Arguments `psi` | object of class psi_func `equation` | equation to base computations on. "location" and "scale" are for the univariate case. The others are for a multivariate location and scale problem. "eta" is for the shape of the covariance matrix, "tau" for the size of the covariance matrix and "mu" for the location. `dimension` | dimension for the multivariate location and scale problem. `desiredEfficiency` | scalar, specifying the desired asymptotic efficiency, needs to be between 0 and 1. `interval` | interval in which to do the root search, passed on to `uniroot`. `...` | passed on to `uniroot`. ``` -------------------------------- ### Plotting Robust Loss Functions Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Visualizes different psi-functions (loss functions) used in robust estimation, including classical, Huber, and smoothed Huber functions. This helps in understanding their behavior and tuning parameters. ```R plot(cPsi) plot(huberPsiRcpp) plot(smoothPsi) curve(cPsi@psi(x), 0, 3, col="blue") curve(smoothPsi@psi(x), 0, 3, add=TRUE) curve(huberPsiRcpp@psi(x), 0, 3, add=TRUE, col="green") ``` -------------------------------- ### View Simulation Study Scripts Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Accesses simulation study script files shipped with the robustlmm package. Allows creating editable copies of these scripts. ```R viewCopyOfSimulationStudy( study = c("sensitivityCurves.R", "consistencyAndEfficiencyDiagonal.R", "consistencyAndEfficiencyBlockDiagonal.R", "breakdown.R", "convergence.R", "robustnessDiagonal.R", "robustnessBlockDiagonal.R"), destinationPath = getwd(), overwrite = FALSE ) ``` ```R ## Not run: viewCopyOfSimulationStudy("sensitivityCurves") ## End(Not run) ``` -------------------------------- ### Process Fitted Objects (lmerMod method) Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html This S3 method processes fitted objects of class 'lmerMod' to convert them into a data structure suitable for post-processing. Control which components (coefficients, standard errors, residuals, etc.) are extracted using logical arguments. ```R processFit( obj, all = FALSE, coefs = TRUE, stdErrors = all, tValues = all, sigma = TRUE, thetas = TRUE, b = all, meanB = all, meanAbsB = all, residuals = all, converged = TRUE, numWarnings = all, procTime = all, ... ) ``` ```R processFit( obj, all = FALSE, coefs = TRUE, stdErrors = all, tValues = all, sigma = TRUE, thetas = TRUE, b = all, meanB = all, meanAbsB = all, residuals = all, converged = TRUE, numWarnings = all, procTime = all, ... ) ``` -------------------------------- ### Generate and Process ANOVA Datasets Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Generates datasets for ANOVA and processes them using different fitting methods including lmer, rlmer_DASvar, heavyLme, and lqmm. Some fitting methods are computationally intensive and marked as 'Not run'. ```R set.seed(1) oneWay <- generateAnovaDatasets(1, 1, 10, 4, lmeFormula = y ~ 1, heavyLmeRandom = ~ 1, heavyLmeGroups = ~ Var2, lqmmRandom = ~ 1, lqmmGroup = "Var2", groups = cbind(rep(1:4, each = 10), rep(1:10, 4)), varcov = matrix(1, 4, 4), lower = 0) processFit(fitDatasets_lmer(oneWay)[[1]], all = TRUE) processFit(fitDatasets_rlmer_DASvar(oneWay)[[1]], all = TRUE) ## Not run: processFit(fitDatasets_heavyLme(oneWay)[[1]], all = TRUE) ## End(Not run) if (require(lqmm)) { processFit(fitDatasets_lqmm(oneWay)[[1]], all = TRUE) } ## Not run: processFit(fitDatasets_varComprob_compositeTau(oneWay)[[1]], all = TRUE) ## End(Not run) ``` -------------------------------- ### Source Robustness Block Diagonal Simulation Study Source: https://cran.r-project.org/web/packages/robustlmm/vignettes/simulationStudies.Rnw Sources the R script for the block diagonal case simulation study. This script is used to generate the data and results for Figures 4 and 5 in Koller et al. (2022). ```r source(system.file("simulationStudy/robustnessBlockDiagonal.R", package = "robustlmm")) ``` -------------------------------- ### Bind Generated Datasets in R Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Combines multiple datasets generated with different random generators into a single dataset. Ensure the underlying dataset structure is identical before binding. ```r datasets1 <- generateAnovaDatasets(2, 4, 4, 4) datasets2 <- generateAnovaDatasets(2, 4, 4, 4) datasets <- bindDatasets(datasets1, datasets2) data <- datasets$generateData(1) stopifnot(data$numberOfDatasets == 4, all.equal(datasets2$generateData(1), datasets$generateData(3), check.attributes = FALSE), all.equal(datasets2$sphericalRandomEffects(1), datasets$sphericalRandomEffects(3)), all.equal(datasets2$createXMatrix(data), datasets$createXMatrix(data)), all.equal(datasets2$createZMatrix(data), datasets$createZMatrix(data))) ``` ```r preparedDataset <- prepareMixedEffectDataset(Reaction ~ Days + (Days|Subject), sleepstudy) datasets1 <- generateMixedEffectDatasets(2, preparedDataset) datasets2 <- generateMixedEffectDatasets(2, preparedDataset) datasets <- bindDatasets(datasets1, datasets2) data <- datasets$generateData(1) stopifnot(data$numberOfDatasets == 4, all.equal(datasets2$generateData(1), datasets$generateData(3), check.attributes = FALSE), all.equal(datasets2$sphericalRandomEffects(1), datasets$sphericalRandomEffects(3)), all.equal(datasets2$createXMatrix(data), datasets$createXMatrix(data)), all.equal(datasets2$createZMatrix(data), datasets$createZMatrix(data))) ``` -------------------------------- ### Fit Datasets with varComprob (compositeS, OGK) Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Fits variance components models using the varComprob function with the compositeS and OGK methods. Allows specifying post-fitting actions and dataset indices. ```R fitDatasets_varComprob_compositeS_OGK( datasets, postFit, datasetIndices = "all" ) ``` -------------------------------- ### Compare Fits of lmerMod or rlmerMod Objects in R Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Compares estimated parameters from multiple lmerMod or rlmerMod fits. Useful for quickly assessing differences between models. ```r compare(..., digits = 3, dnames = NULL, show.rho.functions = TRUE) ``` ```r getInfo(object, ...) ``` ```r xtable( x, caption = NULL, label = NULL, align = NULL, digits = NULL, display = NULL, ... ) ``` ```r print( x, add.hlines = TRUE, latexify.namescol = TRUE, include.rownames = FALSE, ... ) ``` ```r getInfo(object, ...) ``` -------------------------------- ### Fit Datasets with varComprob (S, OGK) Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Fits variance components models using the varComprob function with the S and OGK methods. Allows specifying post-fitting actions and dataset indices. ```R fitDatasets_varComprob_S_OGK( datasets, postFit, datasetIndices = "all" ) ``` -------------------------------- ### createDatasetsFromList Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Converts a list of data objects into a dataset list format suitable for fitting functions. It allows specifying the formula, true coefficients, and error scale for generating datasets. ```APIDOC ## createDatasetsFromList ### Description Convert a list of datasets to a dataset list similar to the ones created by `generateAnovaDatasets` and `generateMixedEffectDatasets`. ### Usage ```R createDatasetsFromList( datasetList, formula, trueBeta, trueSigma, trueTheta, ... ) ``` ### Arguments `datasetList` | list of data objects, usually of type `data.frame`. `formula` | formula to fit the model using `lmer`. `trueBeta` | scalar or vector with the true values of the fixed effects coefficients. Can be of length one in which case it will be replicated to the required length if needed. `trueSigma` | scalar with the true value of the error scale. `trueTheta` | scalar or vector with the true values for the variance component coefficients, not including sigma. Can be of length one in which case it will be replicated to the required length if needed. `...` | all additional arguments are added to the returned list. ### Details The returned list can be passed to `processFit` and to any of the `fitDatasets` functions. Splitting and binding of datasets using `splitDatasets` and `bindDatasets` is not supported. ### Value list that can be passed to `processFit` and to any of the `fitDatasets` functions. Only `generateData` is implemented, all the other functions return an error if called. ### See Also `generateAnovaDatasets` and `generateMixedEffectDatasets` ### Examples ```R data(sleepstudy) sleepstudy2 <- sleepstudy sleepstudy2[1, "Reaction"] <- sleepstudy2[1, "Reaction"] + 10 fm1 <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy) datasets <- createDatasetsFromList(list(sleepstudy, sleepstudy2), formula = Reaction ~ Days + (Days|Subject), trueBeta = getME(fm1, "beta"), trueSigma = sigma(fm1), trueTheta = getME(fm1, "theta")) fitDatasets_lmer(datasets) ``` ``` -------------------------------- ### Fit Datasets with varComprob (S) Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Fits variance components models using the varComprob function with the S method. Allows specifying post-fitting actions and dataset indices. ```R fitDatasets_varComprob_S(datasets, postFit, datasetIndices = "all") ``` -------------------------------- ### Show PsiFunction object Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Displays an instance of a PsiFunction class, such as Rcpp_SmoothPsi or Rcpp_HuberPsi. This is a standard S4 method for object inspection. ```R show(smoothPsi) ``` -------------------------------- ### Source Robustness Diagonal Simulation Study Source: https://cran.r-project.org/web/packages/robustlmm/vignettes/simulationStudies.Rnw Sources the R script for the diagonal case simulation study. This script is used to generate the data and results for Figures 2 and 3 in Koller et al. (2022). ```r source(system.file("simulationStudy/robustnessDiagonal.R", package = "robustlmm")) ``` -------------------------------- ### Find the Incorrect Root using Root Finding Source: https://cran.r-project.org/web/packages/robustlmm/vignettes/rlmer.R Uses spline interpolation and the uniroot function to find the 'false' root of the difference between realized and expected values. ```R spl <- splinefun(test.1$theta, test.1$difference) false <- uniroot(spl, c(0, with(test.1, theta[which.max(difference)])))$root ``` -------------------------------- ### Fit Datasets with varComprob (compositeS, 2SGS) Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Fits variance components models using the varComprob function with the compositeS and 2SGS methods. Allows specifying post-fitting actions and dataset indices. ```R fitDatasets_varComprob_compositeS_2SGS( datasets, postFit, datasetIndices = "all" ) ``` -------------------------------- ### Fit Datasets with varComprob (S, 2SGS) Source: https://cran.r-project.org/web/packages/robustlmm/refman/robustlmm.html Fits variance components models using the varComprob function with the S and 2SGS methods. Allows specifying post-fitting actions and dataset indices. ```R fitDatasets_varComprob_S_2SGS( datasets, postFit, datasetIndices = "all" ) ``` -------------------------------- ### Source Convergence Simulation Study R Script Source: https://cran.r-project.org/web/packages/robustlmm/vignettes/simulationStudies.Rnw Sources the R script that performs the convergence simulation study. This script is essential for generating the data and results analyzed in the study. ```r source(system.file("simulationStudy/convergence.R", package = "robustlmm")) ```