Least-Squares Means

Obtain least-squares means for linear, generalized linear, and mixed models. Compute contrasts or linear functions of least-squares means, and comparisons of slopes. Plots and compact letter displays. Least-squares means were proposed in Harvey, W (1960) "Least-squares analysis of data with unequal subclass numbers", Tech Report ARS-20-8, USDA National Agricultural Library, and discussed further in Searle, Speed, and Milliken (1980) "Population marginal means in the linear model: An alternative to least squares means", The American Statistician 34(4), 216-221 . NOTE: lsmeans now relies primarily on code in the 'emmeans' package. 'lsmeans' will be archived in the near future.

R package lsmeans: Least-squares means (estimated marginal means)

cran version downloads total downloads Research software impact The lsmeans package is being deprecated. Users are encouraged to switch to emmeans (estimated marginal means), now available on CRAN. The lsmeans package will be archived on CRAN at some not-too-distant time in the future. Note that:

  • R scripts that use lsmeans will still work with emmeans after making minor changes (use emmeans:::convert_scripts()).
  • Existing objects created with lsmeans can be converted to work with the new package via emmeans:::convert_workspace().
  • See vignette("transition-from-lsmeans", "emmeans") for more details.


Changelog for 'lsmeans' package

2.30-0 Deferred almost all functionality to the 'emmeans' package.

2.27-62 Corrected a misleading statement in ?transition

2.27-61 Fixes to vcov calls to pass checks against R-devel

2.27-60 Startup message and Description encouraging users to switch to 'emmeans' Removed 'extending' vignette as we won't be encouraging anyone to add lsmeans support. An updated version exists in 'emmeans'

2.27-22 Improvements to detection of nested effects New 'add_grouping()' function to redefine an existing factor as a nested effect Bug fix in handling 'nesting' argument Handling of contrasts of just one case changed to prevent breaking other things. Instead of an empty grid and a warning, we now get one row named "(nothing)". Defaults for 'adjust' in '[.ref.grid()' and 'rbind.ref.grid()' changed due to all-too-likely high overhead in "mvt"

2.27 Added warning and workaround if user specifies a vector for type Added support for nested structure(s) in the fixed effects. Modifications to summary.ref.grid to suppress output for empty cells in nested structures and handle 'by' groups of varying sizes Added support for variable names having spaces (contr by Jonathon Love) Additional 'weights' option of "flat" Non-estimable cases are now displayed as "nonEst" in the summary Various bug fixes

2.26 Moved code repository to https://github.com/rvlenth/lsmeans Added BugReports: URL to DESCRIPTION In 'cld', get error instead of message if "multcompView" not installed Added warning message in 'predict.ref.grid(..., type = "response")' when transformation is unknown. Added support for models that have BOTH a link function and a response transformation -- and additional prediction type "mu" 'recover.data' warns when there is a call in the model-fitting call, as may happen in simulations. Preliminary support for rstanarm package (stanreg objects) -- but not for stan_betareg, stan_biglm, stan_gamm4 Addition of as.stanfit and as.mcmc.list; extension of as.mcmc to support multiple chains

2.25-5 Added 'coef' method for 'ref.grid': returns the contrast coefficients (if any) generated by 'contrast'. Yet another bug correction for lme support (reverted to old code that worked just fine until I tried to make it more efficient) Improved labeling of lstrends when a contrast is specified Bug fix for error when 'weights' specified but no weights available Bug fix in ordinal support with weights

2.25 Now supports models with just the intercept Added support for lsmeans(model, ~1) or lsmeans(model, "1") so that you may obtain the average over all factors. Corrected bug in lme support when data are subsetted Updated and clarified license info to make it more compatible with licenses of packages that depend on this one

2.24 lsm.options now returns the options visibly if no arguments are provided S4 class definitions modernized to use slots instead of representation 'ref.grid' gets a new 'transform' argument that can be used instead of following it with a call to 'regrid' lstrends now correctly handles response transformations when constructed with transform = "response" lsmeans with a 'trend' argument can now have character 'specs', and is generally more robust to user errors. contrast() now handles log and logit models somewhat differently: - inverse transformations are labeled as ratios whenever all the linear functions sum to 0 (previously just pairwise comparisons) - contrasts of logits are now annotated as being on the "log odds ratio" scale ref.grid and related functions previously did not detect response transformations when model call had no argument named "formula" (e.g., nlme::lme(fixed, random, ...) didn't work) Now can handle not only models where covariates are made into factors, but ones where factors are made into covariates, e.g., y ~ factor(x) + unclass(trt) New option 'lmer.df' and corresponding 'mode' argument for 'merMod' objects, allows user to specify Satterthwaite (new default), K-R, or asymptotic degrees of freedom. CAUTION: This may alter the results obtained by default with 'merMod' objects. Use 'lsm.options(lmer.df = "ken")' if you want the same behavior as before Added a 'df' argument to 'ref.grid' to make it more user-friendly Fixed bug in recover.data.call with incorrect call to 'complete.cases' This fix could change the reference values for covariates from past results - especially for lme models or where 'data' is used Addition to "extending" vignette illustrating how the 'rsm' package supports 'lsmeans' Misc. minor bug fixes and code improvements

2.23-5 More graceful handling of mu.hat <= 0 in regrid(., "log") Added 'predict.type' argument to 'regrid' Bug fixes related to the case where all estimates are NA Addition of 'reversed' argument to 'cld' Bug fixes for na.action handling. Results may now differ somewhat from past versions, especially if you have covariates Fixed bug in 'lstrends' when there is a response transformation Fixed new bug that popped up when tbl_df objects are used Under-the-radar support for Satterthwaite method from lmerTest. To try it: lsm.options(disable.satterth = FALSE)

2.23 Added xtable support (actually uses xtableList) Corrected bugs in rbind.ref.grid that caused error when rank-deficient, and incorrectly reported 'avgd.over' information In summary.ref.grid with type = "response", ensured CIs are never reversed and SEs are always nonnegative Fixed a bug in reverse-transforming estimates and CIs when the a linear predictor is invalid (e.g., a negative sqrt) Greatly increased transformation capabilities via 'make.tran' Made messages more explicit about which transformation is/was used Renamed 'adjustSigma' to 'sigmaAdjust' in 'lme' support to avoid a conflict with 'adjust' Improvements to lsm() which previously did not pass arguments like 'at' and 'by' to ref.grid Added glht.list methods: coef, confint, plot, vcov Added "log" capability to 'regrid' 'using-lsmeans' vignette updated to include more information on 'xtable', 'make.tran', and 'regrid' 'using-lsmeans' now also has a comprehensive index Added .Last.ref.grid feature and lsm.option "save.ref.grid" Expanded options to include null, side, and delta

2.22 If confidence intervals are requested and 'adjust' doesn't make sense (e.g., "fdr"), we now default to "bonferroni" instead of "none", and don't override the adjustment made for tests. 'update.ref.grid' now also allows directly replacing slots. A new 'interaction' argument is added to 'contrast', thus facilitating generation of interaction contrasts. Improvements to 'test' with 'joint = TRUE' Better error message in cases where no estimates are produced. Basic support for 'betareg' objects CITATION file added to reflect related JSS article.

2.21-1 Changed R dependency to >= 3.2; needed for rbind support

2.21 Changed implementation of pbkrtest.limit - now based on number of rows of design matrix. Added support for "hurdle" and zeroinfl" classes (pscl package) In 'regrid', dffun now implements a containment method Additional annotation to clarify when results are on the linear-predictor scale. Added courtesy wrappers pmmeans, pmtreans, pmmip, ... for those who prefer "predicted marginal means" to "least-squares means". Output is re-labeled as well. Export a few hidden fcns of possible use to package developers Updates to "extending" vignette Miscellaneous bug fixes, including repair to d.f. method from regrid

2.20-23 Added 'get.lsm.option()', works like 'getOption()' but with defaults obtained from 'lsmeans::defaults' Added pbkrtest.limit option -- to limit object size of 'lmerMod' objects for which the K-R method is used, to prevent excessive time/memory Fixed bug that occurs with models where the response is not discernible from the call. In plot.lsmobj, int.adjust now defaults to object's 'adjust' setting (as it should have originally)

2.20-2 Fixed error in df for joint tests with aovlist objects (but existing ref.grid objects need to be rebuilt for it to work) Patched problem with rbind with R < 3.2

2.20 Added 'rbind' function for combining ref.grids into one family Added "[.ref.grid" method for subsetting a reference grid Efficiency/robustness improvements to recover.data for certain models Removed 'mixed' support -- afex >= 0.14 has its own lsmeans support Added support for 'nnet::multinom' objects Returned table from 'lsmip' now includes a "lattice" attribute; also an additional 'plotit' argument to control its display Changed DESCRIPTION to produce a clearer citation

2.19 Added optional params argument for ref.grid and related functions - use it to specify variables in the model formula that are not predictors Added optional vcov. argument so user can override the default vcov() with a function or specified matrix Now supports model formulas containing $ and [[]] (and related exported function All.vars) Revised support for survreg, coxph, coxme -- strata and cluster no longer in reference grid. Previous coxme support was bad for other reasons as well Added as.glht method for 'lsm.list', similar to other methods for this class In 'contrast', when 'method' is a list, names are kept as-is whereas previously there was an implicit 'make.names' call Imports of globals from default packages per a change in CRAN checking requirements.

2.18 In DESCRIPTION, moved all Enhances packages to Suggests; Enhancements can't be tested and cause headaches Fixed bug in lstrends - 'data' argument was not used correctly Fixed bug in cld where fatal error occurs when type = "response" Added temporary workaround for 'maov' and 'manova' objects (error in stats coef.maov now fixed in R-devel) Re-enabled existing code for 'mer' support (lme4.0) -- previously had trouble with > 1 Additional_repositories Made "dunnettx"-adjusted critical values more robust Coding improvements for adjusted p values and critical values Added 'consec.lsmc' and 'mean_chg.lsmc' to available contrasts Added support for the CARBayes package

2.17 Removed unneeded import of 'Matrix' (could have done this in 2.12 when I stopped using my own adaptation of 'pbkrtest' code) Bug fix for gls, lme, nlme objects with 'weights' argument Allows for character predictors in models as well as factors Exported selected S3 methods for lsm.basis and recover.data for use by other packages Added 'post.beta' slot in 'ref.grid' and 'lsmobj' classes; if not NA, holds sample from posterior of fixed effects. Also added 'as.mcmc' function to return posterior sample of lsmeans when 'post.beta' has data Added support for 'MCMCglmm' and some 'mcmc' objects produced by the 'MCMCpack' package

2.16 Added support for 'nlme' objects (for parameters in 'fixed') (and associated additional vignette example) Degrees of freedom now produced with lme and nlme objects (uses containment-like method) Addition of 'name' argument in 'contrast' Now built with byte-compiler enabled Bug fix in lstrends when there is a multivariate response Corrected error in annotation for Tukey-adjusted P values Other minor bug fixes and documentation improvements

2.15 Clarified annotations for Tukey and Scheffe-adjusted summaries Moved estimability code to a separate 'estmability' package Basic support for model objects in rms package Explicit non-support for gam (previously ran due to inheritance, but produced the wrong results!)

2.14 Model weights are now used instead of frequencies when weights are not "equal" Fixed error in 'lstrends' when 'specs' is two-sided formula Added more/better references for LS means Yet more enhancements for for clm, clmm, polr... "mean.class" mode, uses response name for "prob" mode "scale" mode does lsmeans for estimated log-scale Enhancements to 'weights' argument in 'lsmeans': - May now provide a matrix - it cycles through its rows - weights = "show.levels" shows the factor comb's averaged Added 'reverse' option to 'pairs' Added 'type' argument in 'ref.grid' for convenience Fixed some errors/omissions in documentation of 'update' One-sided 'tail' spec now applies to CIs as well as tests New adjustment methods added: "mvt" provides exact one-step methods like Tukey, Dunnett "dunnettx" is approximate and only available for 2-sided cases Added contrast fcns "tukey" and "dunnett" - these are pseudonyms for "pairwise" and "trt.vs.ctrl" resp. More adjustments are available for confidence intervals Tries harder to use only appropriate adjust methods New 'estType' attribute for 'update' related to the above 'cld' accommodates when 'multcompView' isn't installed, thus can still pass checks without that package Removed .old.lsmeans and associated vignette

2.13 Provides for equivalence, noninferiority, etc. tests via 'side' and 'delta' arguments in 'summary' or 'test'. Also for non-zero null values via 'null' Added support for ordinal package objects 'clm', 'clmm' Option 'mode' added for 'polr' objects, defaulting to "latent". NOTE - NEED TO SET 'mode = "linear.predictor" TO REPRODUCE PAST RESULTS FOR 'polr' OBJECTS. nlme and lme4 moved to 'Enhances' field for consistency ### Added limited support for mer objects (lme4.0 package) ### I dropped this because it messes-up the CRAN checks Added 'adjustSigma' option for 'lme' objects (works like in 'summary.lme') Fixed error in handling offsets for 'polr' objects Fixed error in omitting modeled covariates when there was a multivariate response. Fixed bug in 'contrast' that failed to update 'pri.vars' which, e.g., creates an error in a subsequent plot Fixed bug in plot - it had ignored xlab when horizontal = FALSE In lsmip with type = "response", the vertical axis is now labeled with misc$inv.lbl when available Removed frequencies and offsets from row labels in 'as.glht' Fixed 'as.glht' so df may be omitted or set to NA for asymptotics Renamed the 'parm' argument in 'test' to 'null' Removed superfluous "P values are asymptotic" messages. Revision to function producing estimates, SEs, and df Added provision to specify 'estHook' and 'vcovHook' in 'misc' slot to allow for custom routines for estimates and covariances. '.is.estble' is renamed 'is.estble' -- exported and documented. The 'by' variable for 'test' now also works when 'joint = TRUE'

2.12 *** Developers supporting lsmeans please note: *** *** Change to lsm.basis prototype: Added a "..." argument *** Removed own patch for df from pbkrtest in favor of its Lb_ddf. This means you must have pbkrtest 0.4-1 or newer Added 'plot.lsmobj' method to display confidence intervals These plots also optionally can display comparison arrows that attempt to display significance of pairwise comparisons according to their degree of overlap Added 'joint' argument to 'test' Fixed a bug in vcov Modified 'auto.noise' so 'side' has levels 'L' and 'R' rather than 'R' and 'L' (so not in reverse position in plots!) Added support for: gee, geeglm, and geese objects (gee, geepack); glmmadmb objects (glmmADMB); mixed objects (afex) Added 'lsmobj' function to construct an lsmobj from summary statistics Overhauled 'lsmeans-package' help page to provide an overview with links to key functions, and integrated details of model-specific implementation in a new 'models' help page

2.11 Added vcov method for ref.grid Added 'weights' argument for lsmeans - may be numeric, or the string "equal", "proportional", "outer", or "cells" Enhanced 'cov.reduce' argument in 'ref.grid' to allow formulas, useful when you think covariates depend on other variables. Also, when cov.reduce is a list, it may now include anything -- function, logical, or formula Additional dataset 'feedlot' Now 'cld' does not break when there are non-estimable lsmeans Fixed situation where one error message masks another more informative one Added possibility of 'summary=' spec for lsm.options, which sets defaults for summary, predict, and lsmip Improvements/updates to vignettes Minor coding/efficiency improvements Removed 'df' arg for ref.grid, stupidly added in 2.10 (we can set df as part of 'options' arg)

2.10 Support for 'aovlist' objects (does intra-block analysis) To use, avoid contr.treatment; use contr.sum or other that sums to 0 Added 'contrast', 'test', 'pairs', 'confint', 'cld' methods for lsm.list, with 'which' argument defaulting to 1 Added 'disable.pbkrtest' option (via lsm.options) if you don't want bias correction and K-R degrees of freedom with lmerMod objects Added 'df' argument to 'ref.grid' constructor, also 'summary' and 'update'.

2.05 Corrected error in Tukey-adjusted confidence intervals New dataset 'oranges' Completely revised, improved vignette 'using-lsmeans' New vignette 'extending lsmeans' New 'mult.name' argument in 'ref.grid' New 'lsm.options' function and associated support for setting display defaults for various objects Improved estimability checking and ability to set the tolerance via lsmeans.options(estble.tol = ...) Added estimability support for merMod, now that lme4 supports rank-deficient models Miscellaneous small improvements to code and datasets

2.00-5 Additional message showing what factors have been averaged over Now adds offsets to predictions when model contains offset() terms (but not for an 'offset' argument) New 'update' method for "ref.grid" objects Broader support for transformations (see ?update.ref.grid) Changed all S3 methods for "lsmobj", except 'show', to S3 methods for the "ref.grid" class, since they all work just fine for this class as well. Added an example for 'lstrends' Removed unneeded misc$ylevs element in ref.grid objects New way to bypass unneeded package-loading from pbkrtest Added an example for lstrends as there wasn't one Fixed minor bug in summary() - a try() call should have been with silent=TRUE

2.00-4 Reverted to code that just loads pbkrtest and its required (but unneeded) packages when pbkrtest is needed

2.00-3 Slight change in use of attach() in lsm.basis.merMod

2.00-2 Added some support for adjusted confidence limits Minor bug fix to make recover.data work with more gls models Fewer unneeded packages are loaded

2.00-1 Fixed a minor formatting issue in a vignette

2.00-0 This is a major redesign of the package. Single function 'lsmeans' is replaced by methods for different types of models and specifications, and returns an 'lsmobj' rather than a 'data.frame'. New functions 'ref.grid', 'contrast', 'lstrends', and new 'summary', 'confint', 'test', 'glht', 'cld' methods for 'ref.grid' and 'lsmobj' objects. See the vignette "lsmeans-changes" for more details. This version is easily extensible to various types of model objects, and several more are supported such as survreg, coxph, polr. There is also full support for na.actions, and for back-transforming results when a response is transformed or a link function is used.

1.10-4 Fixed bug in cld spec that caused multiple letter columns

1.10-3 Added cld capability Fix to lsmip so factor levels are not re-ordered Added new dataset: 'auto.noise' Fixed problem in documentation link to another package

1.10-2 Added simple support for models with a multivariate response Bug fix for case when only one contrast is specified Examples that use lme4 package are made conditional per CRAN requirements since lme4 version 1.0-4 and later depend on a non-portable package Dependency modifications to meet CRAN requirements. Includes adding multcomp as required package, since we enhance glht

1.10-01 Now works again for 'gls' objects

1.10-00 Added contrast families for effects and "deleted effects" Added "scheffe" option for 'adjust' argument Added lsmip function (interaction plots) Fixed Tukey-adjusted P values for d.f. near 2. (Note: ptukey does not work when there are less than 2 d.f.) Allow covariates in 'specs' formula (also allows covariates to have multiple levels and be part of the reference grid that is averaged over in determining LS means) Allow cov.reduce to be logical - mostly to implement a 'unique' option No d.f. or adjusted covariance matrix for GLMMs (questionable validity, plus pbkrtest won't play along) Now checks lengths of contrast coef's for conformity Fixed a bug in estimability checking (occurred when qr.R does not return a square matrix) Efficiency improvements. Now requires 'plyr' package

1.06-06 - June 13, 2013 Added support for lmerMod objects (gitHub version of lme4)

1.06-05 - February 13, 2013 Fixed a bug whereby unused levels of factors can create havoc.

1.06-00 - January 14, 2013 Added a 'trend' argument for estimating and contrasting fitted trends rather than lsmeans

1.05-01 - December 5, 2012 Fixed a bug that occurs when model contains expressions like (a + b + c)^2 or other expressions that expand to interaction terms

1.05-00 - November 2, 2012 Added an 'lf' boolean argument to return the matrices of linear functions without evaluating them Added a function 'lsm' and corresponding method for 'glht'; thus, now we can use lsm() much like mcp() Changed examples with glht to integer df -- due to a recent change in mvtnorm glhargs$df is coerced to an integer before passing, but in lsm() it is up to the user to pass appropriate arguments to glht

1.00-00 - October 19, 2012 Added support for factors in 'at' argument (can use it to restrict results) Added columns with factor levels to lsmeans table - for possible use in plots Extended trt.vs.ctrl.lsmc to accommodate more than one reference level (Thanks to Florent Duyme, ARVALIS - Institut du v?g?tal, for suggesting this) Refinements to print methods, including new class 'data.frame.lsm' to display results the way I want them If 'glhargs' is used, those elements are now of class 'summary.glht'. We can still use those results in the same ways as before Added support for adjustment methods in 'p.adjust' (stats) Included a couple of sample datasets Various small bug fixes (e.g. subsets bug)

0.99-80 - September 19, 2012 Now finds degrees of freedom when appropriate for all but lme objects (For mer objects, get df only if 'pbkrtest' installed) lsmeans tables now show confidence intervals instead of t tests and contrast output shows p values (both assuming df are available) Added a 'conf' argument for confidence level in lsmean intervals Added a 'glhargs' argument; if provided, lsmeans passes its contrasts to the 'glht' function in the 'multcomp' package Added an 'adjust' argument for popular single-step multiplicity corrections (uncorrected, Tukey, Bonferroni, and Sidak) Contrast-generating functions now produce an 'adjust' attribute which provides a default multiplicity-adjustment method The 'check.cells' argument is now deprecated. Instead, we do an actual check of estimability in rank-deficient cases (currently can happen only with 'lm' objects). This check is not optional Renamed the vignette to avoid confusion with the regular documentation Returned object is now assigned class "lsm" which has its own print method.

0.99 - August 27, 2012 Now can handle predictors coerced to 'factor' or 'ordered' Now can handle predictors deleted due to rank deficiency Now can handle models with matrices among the predictors (uses 'cov.reduce' on each column; 'at' not supported for matrix covariate) Added support for gls objects (and documented that it works also for glm and glmer) Added a check for empty cells in the design (relative to the model). This (by default) forces a NA to be outputted for any lsmeans that are corrupted by rank deficiencies Generates a warning if specified factor(s) interact with other predictors Better and more comprehensive vignette Added a whole lot of comments to the code (you won't see these, but be glad, as it greatly aids maintainability) Added error messages for anticipatable user errors Numerous bug fixes and corrections to documentation Still no d.f. or P values. Those could take awhile.

0.90 - August 14, 2012 First release, still needs some refinements and bullet-proofing

Reference manual

It appears you don't have a PDF plugin for this browser. You can click here to download the reference manual.


2.30-0 by Russell Lenth, 3 years ago

Browse source code at https://github.com/cran/lsmeans

Authors: Russell Lenth [aut, cre, cph]

Documentation:   PDF Manual  

Task views: Survival Analysis, Statistics for the Social Sciences

GPL-2 | GPL-3 license

Depends on emmeans, methods

Imported by StroupGLMM.

Suggested by broom.

See at CRAN