gpt4 book ai didi

string - 如何替换公式中的因变量?

转载 作者:行者123 更新时间:2023-12-01 23:10:26 34 4
gpt4 key购买 nike

假设我有一个 R 公式:

fm <- formula(y~x1+x2+x1:x2)

还有一组新的响应结果,y1y2y3。如何通过 for 循环替换公式 fm 中的 y

for (newy in c(y1,y2,y3)){
newfm=formula(...)
}

最佳答案

怎么样:

fm <- formula(y~x1+x2+x1:x2)
for (newy in c("y1","y2","y3")){
newfm <- reformulate(deparse(fm[[3]]),response=newy)
print(newfm)
}
## y1 ~ x1 + x2 + x1:x2
## y2 ~ x1 + x2 + x1:x2
## y3 ~ x1 + x2 + x1:x2

诚然,将公式作为公式处理有点棘手 - 实际上将它们作为字符处理然后使用 reformulateas.formula 更容易。

以 OP 建议的方式执行此操作会很有趣但相当棘手,在 for 循环中使用符号而不是字符 - 即 for (newy in c(y1 ,y2,y3)) 因为在 R 尝试评估它们(并引发错误)之前,必须以某种方式截取这些符号。我看不到如何构造表单

for (newy in c(y1,y2,y3)) {
...
}

工作,因为 R 会在进入 for 循环之前尝试评估 c(y1,y2,y3) ...

关于string - 如何替换公式中的因变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22820396/

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