### Run an emmeans example Source: https://rvlenth.github.io/emmeans/reference/emm_example.html Runs a specific example from the package's system files. Requires the 'biglm' package to be installed and loaded. ```R # Run an example if (require(biglm)) emm_example("qdrg-biglm") #> Loading required package: biglm #> Loading required package: DBI #> #> --- Running code from 'system.file("extexamples", "qdrg-biglm.R", package = "emmeans")' #> #> > bigmod <- biglm(log(conc) ~ source + factor(percent), #> + data = pigs) #> #> > rg1 <- qdrg(log(conc) ~ source + factor(percent), #> + data = pigs, coef = coef(bigmod), vcov = vcov(bigmod), df = bigmod$df.residual) #> #> > emmeans(rg1, "source", type = "response") #> source response SE df asymp.LCL asymp.UCL #> fish 29.8 1.09 Inf 27.7 32.0 #> soy 39.1 1.47 Inf 36.4 42.1 #> skim 44.6 1.75 Inf 41.2 48.1 #> #> Results are averaged over the levels of: percent #> Confidence level used: 0.95 #> Intervals are back-transformed from the log scale #> ``` -------------------------------- ### Run GLHT Example with Multcomp Source: https://rvlenth.github.io/emmeans/reference/glht-support.html This snippet demonstrates how to run a predefined example for GLHT with multcomp. It requires the multcomp package to be installed and loaded. ```R if(require(multcomp, quietly = TRUE)) emm_example("glht-multcomp") ``` -------------------------------- ### Run rsm example Source: https://rvlenth.github.io/emmeans/articles/xtending.html Loads the rsm package and runs an example to demonstrate its functionality. The output of the example is not shown. ```R library("rsm") example("rsm") ### (output is not shown) ### ``` -------------------------------- ### Feedlot Example: Mixed-Effects Model Setup Source: https://rvlenth.github.io/emmeans/articles/predictions.html Sets up a mixed-effects model for the feedlot dataset, centering the entry weight and including diet and herd as factors. A reference grid is then created for prediction. ```R feedlot = transform(feedlot, adj.ewt = ewt - predict(lm(ewt ~ herd))) require(lme4) feedlot.lmer <- lmer(swt ~ adj.ewt + diet + (1|herd), data = feedlot) feedlot.rg <- ref_grid(feedlot.lmer, at = list(adj.ewt = 0)) ``` -------------------------------- ### Run or List emmeans Examples Source: https://rvlenth.github.io/emmeans/reference/index.html Use emm_example() to run or list additional examples provided by the emmeans package. This is helpful for exploring functionality. ```r emm_example() ``` -------------------------------- ### Install emmeans from GitHub Source: https://rvlenth.github.io/emmeans/index.html Installs the latest development version of the emmeans package from GitHub. Ensure remotes and Rtools (for Windows) are installed first. The build_vignettes argument can be omitted to save time if vignettes are not needed. ```R remotes::install_github("rvlenth/emmeans", dependencies = TRUE, build_vignettes = TRUE) ``` -------------------------------- ### List an emmeans example Source: https://rvlenth.github.io/emmeans/reference/emm_example.html Lists the code for a specific example without running it. Useful for inspection or manual execution. ```R # List an example ému_example("qdrg-biglm", list = TRUE) #> # Post hoc analysis of a "biglm" object -- not supported by emmeans #> bigmod <- biglm(log(conc) ~ source + factor(percent), data = pigs) #> #> rg1 <- qdrg(log(conc) ~ source + factor(percent), data = pigs, #> coef = coef(bigmod), vcov = vcov(bigmod), df = bigmod$df.residual) #> #> emmeans(rg1, "source", type = "response") #> #> ## But in this particular case, we could have done it the easy way: #> ## rg1 <- qdrg(object = bigmod) #> ``` -------------------------------- ### Convert emmeans object to MCMC object using coda Source: https://rvlenth.github.io/emmeans/reference/mcmc-support.html This example demonstrates converting an emmeans object to an MCMC object compatible with the 'coda' package. It requires the 'coda' package to be installed. The conversion is useful for further analysis and summarization of MCMC results. ```R if(requireNamespace("coda")) emm_example("as.mcmc-coda") ``` -------------------------------- ### emm_example Source: https://rvlenth.github.io/emmeans/reference/emm_example.html This function is used to run or list additional examples provided with the emmeans package. It's designed to help users explore and understand the package's capabilities by conditionally executing or displaying example code. ```APIDOC ## emm_example ### Description This function exists so as to provide cleaner-looking examples in help files when it must be run conditionally on another package. Typically we want to run the code (`run = TRUE` is the default), or otherwise just list it on the console (`list = TRUE`). ### Usage ``` emm_example(name, run = !list, list = FALSE, ...) ``` ### Arguments * **name** (Character) - Name of file to run. We look for a file with this name (with `".R"` appended) in the system files provided with emmeans. * **run** (Logical) - Choosing whether or not to run the example code. * **list** (Logical) - Choosing whether or not to list the example code. * **...** (Any) - Used only by the developer. ### Examples ```R # List an example emm_example("qdrg-biglm", list = TRUE) # Run an example if (require(biglm)) emm_example("qdrg-biglm") ``` ``` -------------------------------- ### qdrg with biglm Source: https://rvlenth.github.io/emmeans/reference/qdrg.html Use this snippet to create a reference grid from a biglm model. Ensure the biglm package is installed and loaded. ```R if (require(biglm, quietly = TRUE)) emm_example("qdrg-biglm") ``` ```R bigmod <- biglm(log(conc) ~ source + factor(percent), data = pigs) rg1 <- qdrg(log(conc) ~ source + factor(percent), data = pigs, coef = coef(bigmod), vcov = vcov(bigmod), df = bigmod$df.residual) emmeans(rg1, "source", type = "response") ``` -------------------------------- ### Example Usage of emmeans with lqs Source: https://rvlenth.github.io/emmeans/articles/xtending.html Demonstrates how to compute estimated marginal means using the emmeans function with an lqs model. This example verifies the functionality of the custom emm_basis method. ```R emmeans(fake.lts, ~ B | A) ``` -------------------------------- ### Generate xtable from emmGrid object Source: https://rvlenth.github.io/emmeans/reference/xtable.emmGrid.html Example demonstrating how to use the `xtable` method on an `emmGrid` object. This code requires the `xtable` package to be installed and will generate a LaTeX table of estimated marginal means, back-transformed to the response scale. ```R if(requireNamespace("xtable")) emm_example("xtable") #> #> --- Running code from 'system.file("extexamples", "xtable.R", package = "emmeans")' #> #> > pigsint.lm <- lm(log(conc) ~ source * factor(percent), #> + data = pigs) #> #> > pigsint.emm <- emmeans(pigsint.lm, ~percent | source) #> #> > xtable::xtable(pigsint.emm, type = "response") #> % latex table generated in R 4.6.0 by xtable 1.8-8 package #> % Wed May 6 00:04:13 2026 #> \begin{table}[ht] #> \centering #> \begin{tabular}{rrrrrr} #> \hline #> percent & response & SE & df & lower.CL & upper.CL \ #> \hline #> \multicolumn{6}{l}{source = fish}\\ #> 9.0000 & 25.6683 & 2.1101 & 17 & 21.5810 & 30.5296 \ #> 12.0000 & 30.8799 & 2.0727 & 17 & 26.8025 & 35.5777 \ #> 15.0000 & 31.0193 & 2.5500 & 17 & 26.0801 & 36.8941 \ #> 18.0000 & 32.3072 & 2.1685 & 17 & 28.0413 & 37.2222 \ #> \hline #> \multicolumn{6}{l}{source = soy}\\ #> 9.0000 & 34.4135 & 2.3099 & 17 & 29.8695 & 39.6489 \ #> 12.0000 & 39.6314 & 2.6601 & 17 & 34.3984 & 45.6606 \ #> 15.0000 & 39.2286 & 2.6331 & 17 & 34.0487 & 45.1964 \ #> 18.0000 & 42.9000 & 4.9874 & 17 & 33.5686 & 54.8254 \ #> \hline #> \multicolumn{6}{l}{source = skim}\\ #> 9.0000 & 35.1821 & 2.3615 & 17 & 30.5365 & 40.5343 \ #> 12.0000 & 43.1574 & 2.8968 & 17 & 37.4588 & 49.7230 \ #> 15.0000 & 49.6316 & 4.0800 & 17 & 41.7287 & 59.0314 \ #> 18.0000 & 59.8000 & 6.9522 & 17 & 46.7926 & 76.4232 \ #> \hline #> \multicolumn{6}{l}{{\footnotesize Confidence level used: 0.95}}\\ #> #> \multicolumn{6}{l}{{\footnotesize Intervals are back-transformed from the log scale}}\\ #> \end{tabular} #> \end{table} #> ``` -------------------------------- ### Format emmeans Results for Reports Source: https://rvlenth.github.io/emmeans/articles/basics.html Use the `print` method with `export = TRUE` to get results in a structured format suitable for reports. This example demonstrates saving and displaying the summary and annotations. ```R ci <- confint(mcrg, level = 0.90, adjust = "scheffe") xport <- print(ci, export = TRUE) cat("\n") knitr::kable(xport$summary, align = "r") for (a in xport$annotations) cat(paste(a, "
")) cat("
\n") ``` -------------------------------- ### View emmeans results with new defaults Source: https://rvlenth.github.io/emmeans/articles/utilities.html After setting options, new emmeans and contrast results will follow the updated defaults. This example shows the output after changing defaults. ```R pigs.anal.p <- emmeans(pigs.lm, consec ~ percent) pigs.anal.p ``` -------------------------------- ### qdrg with MCMC (coda and lme4) Source: https://rvlenth.github.io/emmeans/reference/qdrg.html This example shows how to use qdrg with MCMC samples from a model fitted using lme4. Requires the coda and lme4 packages. ```R if(require(coda, quietly = TRUE) && require(lme4, quietly = TRUE)) emm_example("qdrg-coda") ``` ```R post <- readRDS(system.file("extdata", "cbpplist", package = "emmeans"))$post.beta rg2 <- qdrg(~size + period, data = lme4::cbpp, mcmc = post, link = "logit") summary(rg2, type = "response") ``` -------------------------------- ### Multivariate ref_grid Example Source: https://rvlenth.github.io/emmeans/reference/ref_grid.html Demonstrates creating a reference grid for a linear model with a multivariate response. The `mult.names` argument is used to specify the name of the multivariate response variable. ```R MOats.lm = lm(yield ~ Block + Variety, data = MOats) ref_grid(MOats.lm, mult.names = "nitro") ``` -------------------------------- ### Check emmGrid Object Class (Another Example) Source: https://rvlenth.github.io/emmeans/articles/basics.html Confirming the class of another `emmGrid` object, demonstrating the consistent return type for emmeans computations. ```R class(EMM.source) ``` -------------------------------- ### qdrg with ordinal regression (clm) Source: https://rvlenth.github.io/emmeans/reference/qdrg.html Demonstrates creating a reference grid from an ordinal regression model fitted with clm from the ordinal package. The ordinal package must be installed. ```R if(require(ordinal, quietly = TRUE)) emm_example("qdrg-ordinal") ``` ```R wine.clm <- clm(rating ~ temp * contact, data = wine) ref_grid(wine.clm) qdrg(object = wine.clm, ordinal.dim = 5) ``` -------------------------------- ### Loading the framing dataset Source: https://rvlenth.github.io/emmeans/articles/messy-data.html Loads the 'framing' dataset from the 'mediation' package. Ensure the 'mediation' package is installed. ```r framing <- mediation::framing ``` -------------------------------- ### Example: Pairwise comparisons within groups Source: https://rvlenth.github.io/emmeans/reference/rbind.emmGrid.html Demonstrates how to perform pairwise comparisons within specific groups (rows or columns) of an `emmGrid` object obtained from a linear model. ```R warp.lm <- lm(breaks ~ wool * tension, data = warpbreaks) warp.rg <- ref_grid(warp.lm) # Do all pairwise comparisons within rows or within columns, ``` -------------------------------- ### Apply a power transformation to LS means Source: https://rvlenth.github.io/emmeans/reference/make.tran.html This example demonstrates applying a specific power transformation (e.g., y^(2/3)) to LS-means using `make.tran` when the model was fitted with that transformation. ```R ptran = make.tran("power", 2/3) emmeans(mod, "treatment", tran = ptran) ``` -------------------------------- ### Plotting emmGrid Objects with emmeans Source: https://rvlenth.github.io/emmeans/articles/basics.html Visualize emmGrid objects using the plot() method. This example demonstrates plotting estimates and confidence intervals for different levels of 'cyl' and 'disp'. ```r mcmod3 <- lm(mpg ~ disp * cyl, data = mtcars) ``` ```r EMM3 <- emmeans(mcmod3, ~ cyl | disp, at = list(cyl = c(4,6,8), disp = c(100,200,300))) plot(EMM3) ``` -------------------------------- ### Get emmeans package options Source: https://rvlenth.github.io/emmeans/articles/utilities.html Retrieve default options for emmeans functions using get_emm_option(). This helps understand the default behavior for displaying results and constructing reference grids. ```R get_emm_option("emmeans") ``` ```R get_emm_option("contrast") ``` ```R get_emm_option("ref_grid") ``` -------------------------------- ### Reproduce Stata's margins command with counterfactuals in R Source: https://rvlenth.github.io/emmeans/articles/FAQs.html This example demonstrates how to reproduce Stata's 'margins' command results in R by using the 'counterfactuals' argument in the emmeans function, particularly for binomial models. ```R margex <- haven::read_dta("https://www.stata-press.com/data/r18/margex.dta") margex.glm <- glm(outcome ~ sex * factor(group) + age, data = margex, family = binomial) emmeans(margex.glm, "sex", counterfactuals = "sex") ``` -------------------------------- ### GLHT with specific contrasts and grouping Source: https://rvlenth.github.io/emmeans/reference/glht-support.html This example performs simultaneous tests for general linear hypotheses, specifying which contrasts to test ('which = 1:2') and grouping the results by 'wool'. It demonstrates a more targeted hypothesis testing approach. ```R summary(glht(warp.lm, emm(pairwise ~ tension | wool, which = 1:2, by = "wool"))) ``` -------------------------------- ### Generate Significance Sets with Multcomp Source: https://rvlenth.github.io/emmeans/reference/CLD.emmGrid.html This example demonstrates generating significance sets for pairwise comparisons using multcomp::cld. Significance sets are indicated by numbers, where estimates sharing the same symbol are significantly different. ```R multcomp::cld(pigs.emm, alpha = 0.1, signif.sets = TRUE) ``` -------------------------------- ### Simulate unbalanced design data in R Source: https://rvlenth.github.io/emmeans/articles/re-engineering-clds.html Simulates data from an unbalanced design with 7 treatments and fits a linear model. This setup is used as a moving example for generating CLDs. ```r set.seed(22.10) mu = c(16, 15, 19, 15, 15, 17, 16) # true means n = c(19, 15, 16, 18, 29, 2, 14) # sample sizes foo = data.frame(trt = factor(rep(LETTERS[1:7], n))) foo$y = rnorm(sum(n), mean = mu[as.numeric(foo$trt)], sd = 1.0) foo.lm = lm(y ~ trt, data = foo) ``` -------------------------------- ### Generate HPD Summary for Emmeans Source: https://rvlenth.github.io/emmeans/reference/hpd.summary.html This example shows how to load the coda package and use emm_example to run a demonstration of hpd.summary on an emmeans object. It displays the HPD summary for different periods and notes that results are on the logit scale. ```R if(require("coda")) emm_example("hpd.summary-coda") #> Loading required package: coda #> #> --- Running code from 'system.file("extexamples", "hpd.summary-coda.R", package = "emmeans")' #> #> > cbpp.rg <- do.call(emmobj, readRDS(system.file("extdata", #> + "cbpplist", package = "emmeans"))) #> #> > cbpp.emm <- emmeans(cbpp.rg, "period") #> #> > hpd.summary(cbpp.emm) #> period emmean lower.HPD upper.HPD #> 1 -1.43 -1.96 -0.894 #> 2 -2.39 -3.13 -1.823 #> 3 -2.52 -3.19 -1.862 #> 4 -2.97 -3.88 -1.998 #> #> Point estimate displayed: median #> Results are given on the logit (not the response) scale. #> HPD interval probability: 0.95 #> #> > summary(pairs(cbpp.emm), type = "response", delta = log(2)) #> contrast odds.ratio lower.HPD upper.HPD p.equiv odds.eq #> period1 / period2 2.60 1.264 4.34 0.210 0.2658 #> period1 / period3 2.90 1.266 5.42 0.114 0.1287 #> period1 / period4 4.64 1.595 9.76 0.026 0.0267 #> period2 / period3 1.14 0.486 2.36 0.918 11.1951 #> period2 / period4 1.78 0.580 4.35 0.604 1.5253 #> period3 / period4 1.55 0.437 4.01 0.700 2.3333 #> #> Point estimate displayed: median #> 'p.equiv' and 'odds.eq' based on posterior P(|lin. pred.| < 0.6931) #> Results are back-transformed from the log odds ratio scale #> HPD interval probability: 0.95 #> # Use emm_example("hpd.summary-coda", list = TRUE) # to see just the code ``` -------------------------------- ### Set emmeans Options on Startup Source: https://rvlenth.github.io/emmeans/reference/emm_options.html Configure default emmeans options by setting the 'emmeans' list in the R system options. This is typically done in the `.Rprofile` file for persistent settings. ```R options(emmeans = list(summary = list(predict.type = "response"), lmer.df = "satterthwaite")) ``` -------------------------------- ### Create a sample dataset Source: https://rvlenth.github.io/emmeans/articles/xtending.html Generates a sample dataset for testing emmeans support with robust regression models. ```R fake = expand.grid(rep = 1:5, A = c("a1","a2"), B = c("b1","b2","b3")) fake$y = c(11.46,12.93,11.87,11.01,11.92,17.80,13.41,13.96,14.27,15.82, 23.14,23.75,-2.09,28.43,23.01,24.11,25.51,24.11,23.95,30.37, 17.75,18.28,17.82,18.52,16.33,20.58,20.55,20.77,21.21,20.10) ``` -------------------------------- ### Create emmGrid and emmeans objects Source: https://rvlenth.github.io/emmeans/articles/confidence-intervals.html Sets up a linear model and creates reference grid and emmeans objects for subsequent analysis. Requires the 'emmeans' package. ```R mod4 <- lm(inverse(conc) ~ source + factor(percent), data = pigs) RG <- ref_grid(mod4) EMM.source <- emmeans(RG, "source") ``` -------------------------------- ### Get an emmeans option Source: https://rvlenth.github.io/emmeans/reference/emm_options.html Retrieve the currently stored value for a specific emmeans option. ```APIDOC ## get_emm_option ### Description Retrieve the currently stored value for a specific emmeans option. ### Usage ```R get_emm_option(x, default = emm_defaults[[x]]) ``` ### Arguments * `x`: Character value - the name of an option to be queried * `default`: Value to return if `x` is not found ### Value `get_emm_option` returns the currently stored option for `x`, or its default value if not found. ``` -------------------------------- ### Configure startup options for emmeans Source: https://rvlenth.github.io/emmeans/articles/utilities.html Customize emmeans package options in your R startup script (.Rprofile) for persistent default settings, such as Satterthwaite degrees of freedom for lmer models and default contrast inference. ```R options(emmeans = list(lmer.df = "satterthwaite", contrast = list(infer = c(TRUE, FALSE)))) ``` -------------------------------- ### Get arguments for emm_basis.lm Source: https://rvlenth.github.io/emmeans/articles/xtending.html Retrieves the arguments for the emm_basis method specific to linear models (lm). ```R args(emmeans:::emm_basis.lm) ``` -------------------------------- ### Get emmeans option Source: https://rvlenth.github.io/emmeans/reference/emm_options.html Retrieve the currently stored option for a given name. If the option is not found, a default value is returned. ```R get_emm_option(x, default = emm_defaults[[x]]) ``` -------------------------------- ### Analyze MOats Data with emmeans Source: https://rvlenth.github.io/emmeans/reference/MOats.html This example demonstrates how to fit a linear model to the MOats data and then use the emmeans package to compute estimated marginal means for yield across different nitrogen concentrations, stratified by oat variety. Requires the 'emmeans' package. ```R MOats.lm <- lm (yield ~ Block + Variety, data = MOats) MOats.rg <- ref_grid (MOats.lm, mult.name = "nitro") emmeans(MOats.rg, ~ nitro | Variety) ``` -------------------------------- ### Perform Contrasts on Re-leveled emmGrid Source: https://rvlenth.github.io/emmeans/articles/utilities.html Once an `emmGrid` is re-leveled, you can perform contrasts on the new factor structure, for example, using `contrast` with a `by` argument. ```R contrast(warp.fac, "consec", by = "wool") ``` -------------------------------- ### Quick and Dirty Reference Grid with qdrg() Source: https://rvlenth.github.io/emmeans/reference/index.html Generate a quick and dirty reference grid using qdrg(). This is a simplified way to create a grid for exploratory analysis. ```r qdrg() ``` -------------------------------- ### Get the tail of an emmGrid object Source: https://rvlenth.github.io/emmeans/reference/rbind.emmGrid.html Returns the last `n` rows of an `emmGrid` object, similar to the base R `tail` function. ```R tail(x, n = 6, ...) ``` -------------------------------- ### Get the head of an emmGrid object Source: https://rvlenth.github.io/emmeans/reference/rbind.emmGrid.html Returns the first `n` rows of an `emmGrid` object, similar to the base R `head` function. ```R head(x, n = 6, ...) ``` -------------------------------- ### Distinguishing Simple Contrast Methods Source: https://rvlenth.github.io/emmeans/reference/contrast.html Illustrates the difference between using a character vector and a list for 'simple' contrasts. The former contrasts combinations, while the latter contrasts factors separately. ```R contrast(warp.emm, simple = c("wool", "tension")) ``` ```R contrast(warp.emm, simple = list("wool", "tension")) ``` -------------------------------- ### Basic pwpp Plot Source: https://rvlenth.github.io/emmeans/reference/pwpp.html Generates a basic pairwise plot of estimated marginal means from a linear model. Ensure ggplot2 and scales are installed. ```r pigs.lm <- lm(log(conc) ~ source * factor(percent), data = pigs) emm = emmeans(pigs.lm, ~ percent | source) pwpp(emm) ``` -------------------------------- ### Plotting Interactions with emmip Source: https://rvlenth.github.io/emmeans/articles/FAQs.html Use emmip to visualize predictions for interactions between factors. This helps in identifying significant effects and guiding post-hoc tests. ```R emmip(model, A ~ B | C) ``` -------------------------------- ### Fit Model and Obtain Initial emmGrid Source: https://rvlenth.github.io/emmeans/articles/utilities.html This snippet demonstrates fitting a generalized least squares model with heterogeneous variances and obtaining an initial `emmGrid` object. ```R warp <- transform(warpbreaks, treat = interaction(wool, tension)) library(nlme) warp.gls <- gls(breaks ~ treat, weights = varIdent(form = ~ 1|treat), data = warp) ( warp.emm <- emmeans(warp.gls, "treat") ) ``` -------------------------------- ### Calculate and Display Vcov for emmGrid Source: https://rvlenth.github.io/emmeans/reference/emmGrid-methods.html Calculates the variance-covariance matrix for an emmGrid object. The example shows the output after applying zapsmall to clean up near-zero values. ```R warp.lm <- lm(breaks ~ wool * tension, data = warpbreaks) warp.emm <- emmeans(warp.lm, ~ tension | wool) vcov(warp.emm) |> zapsmall() ``` -------------------------------- ### Run Simple Comparisons with contrast() Source: https://rvlenth.github.io/emmeans/articles/confidence-intervals.html Use the `simple` argument in `contrast()` to perform comparisons where contrasts are run using all variables except the specified ones as `by` variables. This is useful for examining specific factor level differences within a model. ```r mod5 <- lm(inverse(conc) ~ source * factor(percent), data = pigs) RG5 <- ref_grid(mod5) contrast(RG5, "consec", simple = "percent") ``` -------------------------------- ### Transforming Estimated Marginal Means Source: https://rvlenth.github.io/emmeans/reference/contrast.html Apply scaling and offset to estimated marginal means, for example, to convert Celsius to Fahrenheit. Confidence intervals are adjusted accordingly. ```R mod <- lm(Water.Temp ~ poly(stack.loss, degree = 2), data = stackloss) (emm <- emmeans(mod, "stack.loss", at = list(stack.loss = 10 * (1:4)))) ``` ```R confint(contrast(emm, "identity", scale = 9/5, offset = 32)) ``` -------------------------------- ### Create Reference Grid with ref_grid() Source: https://rvlenth.github.io/emmeans/reference/index.html Use ref_grid() to create a reference grid from a fitted model. This is a foundational step for many emmeans analyses. ```r ref_grid() ``` -------------------------------- ### Get emmeans on standardized scale Source: https://rvlenth.github.io/emmeans/articles/transformations.html Obtain estimated marginal means directly on the standardized scale of the response variable. The results are presented on the scale of `scale(strength)`. ```R emmeans(fiber.lm, "machine") # on the standardized scale ``` -------------------------------- ### Comparing ref_grid Grids Source: https://rvlenth.github.io/emmeans/reference/ref_grid.html Examine the grid structure of two reference grids to understand differences in their construction, particularly regarding weights. ```R rg.default@grid ``` ```R rg.at@grid ``` -------------------------------- ### Get Default Reference Grid Size Source: https://rvlenth.github.io/emmeans/articles/messy-data.html Calculates and displays the number of rows in the linear function slot of the default reference grid. This indicates the storage requirements. ```r nrow(linfct(rg.usual)) ``` -------------------------------- ### Fit GLM and get estimated probabilities Source: https://rvlenth.github.io/emmeans/articles/transformations.html Fit a generalized linear model and obtain estimated probabilities for each level of a factor. The results are back-transformed from the logit scale. ```r neuralgia.glm <- glm(Pain ~ Treatment * Sex + Age, family = binomial(), data = neuralgia) neuralgia.emm <- emmeans(neuralgia.glm, "Treatment", type = "response") ``` ```text ## Treatment prob SE df asymp.LCL asymp.UCL ## A 0.211 0.1110 Inf 0.0675 0.497 ## B 0.121 0.0835 Inf 0.0285 0.391 ## P 0.866 0.0883 Inf 0.5927 0.966 ## ## Results are averaged over the levels of: Sex ## Confidence level used: 0.95 ## Intervals are back-transformed from the logit scale ``` -------------------------------- ### Simulate Regression Coefficients and Obtain EMMs Source: https://rvlenth.github.io/emmeans/reference/regrid.html This example demonstrates simulating a sample of regression coefficients using `regrid` with `N.sim` and then obtaining EMMs on the response scale. This is useful for generating prediction intervals or performing Bayesian-like inference. ```r # Simulate a sample of regression coefficients set.seed(2.71828) rgb <- regrid(rg, N.sim = 200, transform = "pass") #> Simulating a sample of size 200 of regression coefficients. emmeans(rgb, "source", type = "response") ## similar to emm1 #> source response lower.HPD upper.HPD #> fish 29.8 27.7 31.9 #> soy 39.3 36.5 41.8 #> skim 44.7 41.7 48.3 #> #> Results are averaged over the levels of: percent #> Point estimate displayed: median #> Results are back-transformed from the log scale #> HPD interval probability: 0.95 ``` -------------------------------- ### Get Cell Means for Interacting Factors Source: https://rvlenth.github.io/emmeans/articles/AQuickStart.html Obtain estimates of cell means when two factors interact significantly. This provides the means for each combination of factor levels. ```R EMM <- emmeans(model, ~ treat * dose) EMM # display the cell means ``` -------------------------------- ### Tabulate Source and Percent Levels Source: https://rvlenth.github.io/emmeans/articles/basics.html Use `with(pigs, table(source, percent))` to create a contingency table showing the distribution of `source` and `percent` levels. This helps identify imbalances in sample sizes. ```R with(pigs, table(source, percent)) ``` -------------------------------- ### Create Default Reference Grid Source: https://rvlenth.github.io/emmeans/articles/messy-data.html Constructs a standard reference grid using `ref_grid` without specifying nuisance factors. Useful for understanding the full grid size before optimization. ```r rg.usual <- ref_grid(mtcars.lm) rg.usual ``` -------------------------------- ### Enhancing emmip Plots with ggplot2 Source: https://rvlenth.github.io/emmeans/articles/basics.html Customize interaction plots generated by emmip using ggplot2. This example adds data points and confidence intervals to an emmip plot. ```r require("ggplot2") emmip(mod4, ~ percent | source, CIs = TRUE, type = "response") + geom_point(aes(x = percent, y = conc), data = pigs, pch = 2, color = "blue") ``` -------------------------------- ### Calculate Estimated Marginal Means (EMMs) in R Source: https://rvlenth.github.io/emmeans/articles/basics.html Use the `emmeans()` function to compute estimated marginal means for model factors. Results are on the inverse scale in this example. ```r (EMM.source <- emmeans(mod4, "source")) ``` ```r (EMM.percent <- emmeans(mod4, "percent")) ``` -------------------------------- ### GLHT on emmeans with combined grouping Source: https://rvlenth.github.io/emmeans/reference/glht-support.html This example converts pairwise comparisons of emmeans to GLHT format, but without separating the results by group ('by = NULL'). This provides a single set of simultaneous tests across all combinations of factors. ```R summary(as.glht(pairs(warp.emm), by = NULL)) ``` -------------------------------- ### Fit lm model and calculate emmeans for source Source: https://rvlenth.github.io/emmeans/reference/pigs.html Fits a linear model to the 'pigs' dataset using an inverse transformation of the 'conc' variable and then calculates the estimated marginal means for the 'source' factor. Results are averaged over 'percent' and presented on the inverse scale. ```R pigs.lm <- lm(inverse(conc) ~ source + factor(percent), data = pigs) emmeans(pigs.lm, "source") ``` -------------------------------- ### Fit Linear Model and Calculate EMMs for Feedlot Data Source: https://rvlenth.github.io/emmeans/reference/feedlot.html This example demonstrates fitting a linear model to the feedlot data and then calculating estimated marginal means (EMMs) for diet, stratified by herd. It uses the `cov.reduce` argument to specify a separate reference value of `ewt` for each herd, replicating a specific table from the referenced paper. ```R feedlot.lm <- lm(swt ~ ewt + herd*diet, data = feedlot) # Obtain EMMs with a separate reference value of ewt for each # herd. This reproduces the last part of Table 2 in the reference emmeans(feedlot.lm, ~ diet | herd, cov.reduce = ewt ~ herd) ``` -------------------------------- ### Modifying Reference Grids with cov.reduce Source: https://rvlenth.github.io/emmeans/articles/basics.html Use 'cov.reduce' in ref_grid to specify dependencies between covariates, ensuring sensible values are used for prediction. This example models 'disp' as a function of 'cyl'. ```r mcrg <- ref_grid(mcmod3, at = list(cyl = c(4,6,8)), cov.reduce = disp ~ cyl) mcrg @ grid ``` ```r plot(mcrg) ``` -------------------------------- ### Calculate and Display Emmeans with Custom Options Source: https://rvlenth.github.io/emmeans/articles/basics.html The `emmeans()` function can directly accept arguments like `level` and `infer` which are passed to its `summary()` method. This allows for customized output directly upon calculation. ```r # equivalent to summary(emmeans(mod4, "percent"), level = 0.90, infer = TRUE)) emmeans(mod4, "percent", level = 0.90, infer = TRUE) ``` ```r ## percent emmean SE df lower.CL upper.CL t.ratio p.value ## 9 0.0322 0.001030 23 0.0305 0.0340 31.240 <0.0001 ## 12 0.0270 0.000969 23 0.0253 0.0287 27.872 <0.0001 ## 15 0.0263 0.001100 23 0.0244 0.0282 23.802 <0.0001 ## 18 0.0241 0.001340 23 0.0218 0.0264 18.009 <0.0001 ## ## Results are averaged over the levels of: source ## Results are given on the inverse (not the response) scale. ## Confidence level used: 0.9 ``` -------------------------------- ### Feedlot Example: Reference Grid Sigma Source: https://rvlenth.github.io/emmeans/articles/predictions.html Shows the default standard deviation estimate automatically extracted and stored in the reference grid's misc slot for the feedlot model. ```R feedlot.rg@misc$sigma ``` -------------------------------- ### Test custom contrast function Source: https://rvlenth.github.io/emmeans/articles/comparisons.html Tests the custom 'skip_comp.emmc' function with different parameters to demonstrate its output for various skip and reverse settings. ```R skip_comp.emmc(1:5) ``` ```R skip_comp.emmc(1:5, skip = 0, reverse = TRUE) ``` -------------------------------- ### Get emmeans on coded scale Source: https://rvlenth.github.io/emmeans/articles/xtending.html Calculates estimated marginal means (emmeans) for a response surface model on the coded scale. Specify predictor values using the 'at' argument. ```R emmeans(CR.rs2, ~ x1 * x2, mode = "coded", at = list(x1 = c(-1, 0, 1), x2 = c(-2, 2))) ``` -------------------------------- ### Create Reference Grid in R Source: https://rvlenth.github.io/emmeans/articles/basics.html Generate a reference grid of all factor combinations using `expand.grid()`. This grid is used for obtaining model predictions. ```r (RG <- expand.grid(source = levels(pigs$source), percent = unique(pigs$percent))) ``` -------------------------------- ### Get emtrends on standardized scale Source: https://rvlenth.github.io/emmeans/articles/transformations.html Calculate estimated marginal trends (slopes) for a predictor variable on the standardized response scale. The trend is calculated with respect to the specified variable, `diameter`. ```R emtrends(fiber.lm, "machine", var = "diameter") ``` -------------------------------- ### Get emmeans on original response scale Source: https://rvlenth.github.io/emmeans/articles/transformations.html Back-transform the estimated marginal means to the original response scale. This is achieved by specifying `type = "response"` to undo the standardization. ```R emmeans(fiber.lm, "machine", type = "response") # strength scale ``` -------------------------------- ### Manage emmeans Options Source: https://rvlenth.github.io/emmeans/reference/index.html Set or change emmeans options using emm_options(), get_emm_option(), and with_emm_options(). emm_defaults provides the default option values. ```r emm_options() ``` ```r get_emm_option() ``` ```r with_emm_options() ```