You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行emmeans官方示例代码调用cld函数报错,寻求解决方法

解决emmeans中cld()函数报错的方案

你碰到的两个错误,核心原因是当前版本的emmeans已不再对外导出cld()函数,且multcomp包的cld()方法不支持emmGrid类型对象。下面是三种可行的解决办法:

方法一:安装并加载multcompView包(推荐)

multcompView包专门提供了适配emmGrid对象的cld()方法,步骤很简单:

  1. 先安装包(如果还没装过):
install.packages("multcompView")
  1. 加载包后重新运行你的代码:
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)
foo.emm = emmeans(foo.lm, "trt")

library(multcomp)
library(multcompView)  # 新增加载这个包
cld(foo.emm)

方法二:转换为multcomp支持的对象格式

把emmGrid对象转成multcomp能识别的glht对象,再调用cld():

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)
foo.emm = emmeans(foo.lm, "trt")

library(multcomp)
# 转换为glht对象
foo.glht = glht(foo.lm, linfct = emmeans:::linfct.emmGrid(foo.emm))
cld(foo.glht)

方法三:直接调用emmeans内部方法

如果不想额外装包,可以直接调用emmeans里未对外公开的cld.emmGrid方法,但要注意这种方法可能在未来版本中失效:

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)
foo.emm = emmeans(foo.lm, "trt")

# 调用内部方法
emmeans:::cld.emmGrid(foo.emm)

内容的提问来源于stack exchange,提问作者hnguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:57:06