假设我们有一个公式:
f1 <- y ~ x1
我们需要在此基础上添加协变量sin(2*pi*x2)
,使用一个接受x2
作为参数的函数进行操作。
当然,这个可以运行:update(f1, . ~ . + sin(2 * pi * x2)
但我需要一个像下面这样的函数:
updf <- function(formula, x){
formula <- update(formula, paste("~ . +", sin(2 * pi * x)))
formula}
调用updf(f1,"x2")
将返回:y ~ x1 + sin(2 * pi * x2)
。但是该调用会返回错误信息:"Error in 2 * pi * x : non-numeric argument to binary operator"。
如何解决这个问题?
formula <- update(formula, paste("~ . + sin(2 * pi * ", x, ")"))
就可以解决问题了。 - Oliver