公式操作(按正确顺序放置交互项)

Formula manipulation (place interaction terms in proper order)

我正在尝试建立一个模型验证工具,我在其中遵循前向选择方法,所以如果我们假设我的模型是

model <- y ~ a * b + c * d + e

我可以使用terms函数

attributes(terms(model))$term.labels

找出我模型中的所有预测变量,但这种方法的问题是交互项总是放在结果的末尾。我希望 a:bab 之后,而不是最后,c:d 也是如此。有没有办法保持交互项的顺序?

最简单的方法是在 terms.formula()

中使用 keep.order
model <- y ~ a * b + c * d + e
labels(terms(model, keep.order = TRUE))
# [1] "a"   "b"   "a:b" "c"   "d"   "c:d" "e"  

要查找帮助文件,您需要使用 ?terms.formula,因为 ?terms 中未显示此方法。但是 terms() 调度到公式方法。此外,labels() 是从 terms().

获取术语标签的 shorthand 方法