假设我有一个R公式,这样:
fm <- formula(y~x1+x2+x1:x2)
Run Code Online (Sandbox Code Playgroud)
和一组新的响应的结局,y1
,y2
,y3
.我怎么能通过循环替换y
公式?fm
for
for (newy in c(y1,y2,y3)){
newfm=formula(...)
}
Run Code Online (Sandbox Code Playgroud)
怎么样:
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
Run Code Online (Sandbox Code Playgroud)
将公式作为公式处理无疑是有点棘手的 - 它实际上更容易将它们作为字符处理然后使用reformulate
或as.formula
.
以OP建议的方式执行此操作会很有趣但相当棘手,使用符号而不是for
循环中的字符- 即for (newy in c(y1,y2,y3))
因为符号在R试图评估它们之前必须以某种方式被拦截(并抛出错误) .我看不出如何构建表单
for (newy in c(y1,y2,y3)) {
...
}
Run Code Online (Sandbox Code Playgroud)
工作,因为R会c(y1,y2,y3)
在进入for循环之前尝试评估...