gpt4 book ai didi

r - 带有许多变量的公式中的星号 : how to limit order of interactions?

转载 作者:行者123 更新时间:2023-12-05 09:28:46 25 4
gpt4 key购买 nike

假设我有一个统计模型的变量名称列表 x = c('a','b','c','d','e')。构建 formula 时, 最好使用类似 paste('y ~',paste(x,collapse=' + ')) 的东西来获取 y ~ a + b + c + d + e,尤其是当 x 可能改变时。

现在我想对交互项做同样的事情,但是 paste(x,collapse=' : ') 生成 a : b : c : d : e,它只是一个术语,paste(x,collapse=' * ') 产生 a * b * c * d * e,它包括所有可能的交互跨所有订单——即 a + b + c + ... + a:b + a:c + ... a:b:c + a:b:d + ... + a:b: c:d:e。我怎样才能将交互项的顺序限制为第二,例如a:b ?

最佳答案

假设您想将所有项交叉到指定的程度,实现这一点的最直接方法是在公式中使用 ^ 运算符。

x = c('a','b','c','d','e')

# Build formula using reformulate
(fm <- reformulate(x, "y"))
y ~ a + b + c + d + e

# Cross to second degree
(fm2 <- update(fm, ~ .^2))
y ~ a + b + c + d + e + a:b + a:c + a:d + a:e + b:c + b:d + b:e +
c:d + c:e + d:e

# Terms of f2 as character:
attr(terms.formula(fm2), "term.labels")
[1] "a" "b" "c" "d" "e" "a:b" "a:c" "a:d" "a:e" "b:c" "b:d" "b:e" "c:d" "c:e" "d:e"

# Cross to third degree
(fm3 <- update(fm, ~ .^3))
y ~ a + b + c + d + e + a:b + a:c + a:d + a:e + b:c + b:d + b:e +
c:d + c:e + d:e + a:b:c + a:b:d + a:b:e + a:c:d + a:c:e +
a:d:e + b:c:d + b:c:e + b:d:e + c:d:e

关于r - 带有许多变量的公式中的星号 : how to limit order of interactions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71136009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com