在R中使用变量更新update()中的公式

7

我试图在R的模型公式中添加术语。如果我直接将变量名称输入更新函数,则使用update()可以轻松完成此操作。但是,如果变量名称在一个变量中,则无法正常工作。

myFormula <- as.formula(y ~ x1 + x2 + x3)
addTerm <- 'x4'

#Works: x4 is added
update(myFormula, ~ . + x4)
Output: y ~ x1 + x2 + x3 + x4

#Does not work: "+ addTerm" is added instead of x4 being removed
update(myFormula, ~ . + addTerm)
Output: y ~ x1 + x2 + x3 + addTerm

通过使用变量添加x4可以采用稍微复杂一些的方式来完成。

formulaString <- deparse(myFormula)
newFormula <- as.formula(paste(formulaString, "+", addTerm))
update(newFormula, ~.)
Output: y ~ x1 + x2 + x3 + x4

有没有一种方法可以直接让update()执行此操作而不需要这些额外步骤?我已经尝试过paste、parse和其他常用函数,但它们都不起作用。
例如,如果使用paste0,则输出为:
update(myFormula, ~ . + paste0(addTerm))
Output: y ~ x1 + x2 + x3 + paste0(addTerm)

有谁有关于如何在update()中使用变量的建议吗?

谢谢

1个回答

15

你可能只需执行以下操作:

update(myFormula, paste("~ . +",addTerm))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接