【问题标题】:How to replace the dependent variable in a formula?如何替换公式中的因变量?
【发布时间】:2014-04-02 18:48:38
【问题描述】:

假设我有一个 R 公式:

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

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

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

【问题讨论】:

  • 你可以用例子给出答案吗?
  • 你能不能先看看,看看能不能帮你解决自己的问题?
  • 令我沮丧的是原始公式中的交互项以及如何将其索引到reformulate 参数。
  • 查看terms(fm) 获取索引

标签: string r formula


【解决方案1】:

怎么样:

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) ...

【讨论】:

  • 干得好,本! +1
【解决方案2】:

或者试试这个:

for (i in 1:3) {
    as.formula(paste0("y",i,"~x1+x2+x1:x2"))
}

【讨论】:

  • 为什么需要stringi::stri_paste?来自基础 R 的 paste0 有什么问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
相关资源
最近更新 更多