r - 可以指定 R 中 lm() 中主效应与交互项的顺序吗?
问题描述
我有一个线性模型,重要的是要按特定顺序输入这些术语,因为我计划使用 I 型方差分析。我希望模型包括前两个主要影响及其在第三个主要影响之前的相互作用。
但是,当我将其作为公式输入 时lm()
,它仍然会首先为我提供所有三个主要效果的输出,然后是交互作用。这可以改变吗?
## Example data:
df <- structure(list(x1 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L,3L, 3L, 3L, 3L, 3L),
.Label = c("A", "B", "C"), class = "factor"),
x2 = c(0L, 1L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 1L, 1L, 0L, 0L, 1L,
0L, 1L, 0L, 1L, 1L, 0L, 0L),
x3 = c(1L, 3L, 4L, 5L, 2L, 3L, 3L, 4L, 5L, 1L, 3L, 4L, 5L, 6L, 4L, 3L, 4L,
1L, 2L, 2L, 1L, 1L, 3L, 2L),
y = c(49.5, 62.8, 46.8, 57, 59.8, 58.5, 55.5, 56, 62.8, 55.8, 69.5, 55, 62,
48.8, 45.5, 44.2, 52, 51.5, 49.8, 48.8, 57.2, 59, 53.2, 56)),
class = "data.frame", row.names = c(NA, -24L))
## formula using desired order:
mod1 <- lm(y ~ x1 + x2 + x1:x2 + x3 + x1:x3 + x2:x3 + x1:x2:x3, data=df)
## standard formula:
mod2 <- lm(y ~ x1*x2*x3, data=df)
## same order in anova output:
anova(mod1)
anova(mod2)
## test to show coefficient order affects outputs:
## (but can only change main effects around)
anova(mod2 <- lm(y ~ x1*x2*x3, data=df))
anova(mod3 <- lm(y ~ x1*x3*x2, data=df))
解决方案
事实证明可以使用terms
对象:
mod_terms<-terms(y ~ x1 + x2 + x1:x2 + x3 + x1:x3 + x2:x3 + x1:x2:x3, keep.order=T)
mod3 <- lm(mod_terms, data=df)
anova(mod3)
推荐阅读
- java - 调用枚举的抽象方法
- php - PHP, jQuery (AJAX) - 刷新信息
- selenium-ide - 如何获取 Selenium IDE 中每个命令可用的定位器(目标)的完整列表?
- javascript - 渲染 Handlebars 模板时出现错误“unexpected char '#'”
- c++ - 奇怪的重复模板模式和无限递归
- python - 检查动态数组
- c# - 如何根据配置切换 EF Core 使用的数据库提供程序?
- sql-server - TFS GIT 获取完整错误 TF30042。tbl_content 已满
- css - Google 字体和 Sass 的问题
- typescript - cypress.should 包含带有变量和子字符串的正则表达式