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

在R语言线性模型中如何指定对比以比较多组加权均值?

解决方案

要实现样本量加权的均值对比,你需要基于各组样本量构建对应的效应编码对比矩阵,具体操作如下:

  1. 明确各组样本量
    从你的随机抽样结果中,setosa有19个观测,versicolor有25个,virginica有26个,另外两组的总样本量为25+26=51。

  2. 构建加权对比矩阵
    第一个对比列要直接输出setosa均值 - 另外两组加权联合均值的结果,系数需按样本量比例设置:

    • setosa的系数为1
    • versicolor的系数为-25/51(负的自身样本量占另外两组总样本的比例)
    • virginica的系数为-26/51(同理)

    第二个对比只需和第一个正交即可,这里我们用区分versicolor和virginica的加权对比(可根据需求替换为其他正交形式)。

  3. 替换代码中的问号部分
    直接将构建好的对比矩阵赋值给contrasts(df$Species),完整代码如下:

set.seed(5)
df <- iris[sample.int(nrow(iris), 70), c("Sepal.Length", "Species")]
table(df$Species)
mean(df$Sepal.Length[df$Species == "setosa"])
mean(df$Sepal.Length[!df$Species == "setosa"])

# 构建加权效应编码对比矩阵
n_setosa <- table(df$Species)[["setosa"]]
n_versi <- table(df$Species)[["versicolor"]]
n_virgi <- table(df$Species)[["virginica"]]
n_other <- n_versi + n_virgi

contrasts(df$Species) <- matrix(
  c(
    1, 0,  # setosa的两个对比系数
    -n_versi/n_other, n_virgi/n_other,  # versicolor的两个对比系数
    -n_virgi/n_other, -n_versi/n_other  # virginica的两个对比系数
  ),
  ncol = 2,
  byrow = TRUE,
  dimnames = list(c("setosa", "versicolor", "virginica"), c("Setosa_vs_Other", "Versi_vs_Virgi"))
)

res <- lm(Sepal.Length~Species, df)
# 验证系数是否符合预期
stopifnot(mean(df$Sepal.Length[df$Species == "setosa"])-mean(df$Sepal.Length[!df$Species == "setosa"]) == coef(res)[2])

关键说明

  • 第一个对比列Setosa_vs_Other的系数设计,确保模型的第二个系数恰好等于setosa均值 - 另外两组加权联合均值,加权逻辑完全基于各组样本量占比。
  • 第二个对比列Versi_vs_Virgi与第一个对比正交,仅用于区分另外两组的均值差异,不影响第一个对比的结果准确性。

内容的提问来源于stack exchange,提问作者Caspar van Lissa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 10:47:50