将 R 表达式传递给函数,然后更改其输入参数
我想将 R 表达式传递给自己编写的函数,而不需要 首先评估它,然后操纵输入参数 该函数中的 R 表达式。
我想,用一个例子更容易解释。
在下面的示例函数 fun1
中,应采用 lm(y ~ x, data=datatrain)
作为参数,不带 一开始评价,我想更换 lm(y ~ x, data=datatrain)
中的 datatrain
通过 函数内的 newdatatrain
(更准确地说, newdatatrain
将是带有一些列的 datatrain
在函数内排列)。
我需要提供 lm(y ~ x, data=datatrain) 的原因 作为函数参数,函数应该 也能够采用其他类型的模型以及可能的其他模型 输入参数(例如, randomForest::randomForest(y ~ x, data=datatrain, Replace=FALSE)
)。
这是我尝试过的:
# Does not run through:
fun1 <- function(mycall) {
obj <- quote(mycall)
newdatatrain <- data.frame(y=c(0.22, 1.09, 0.93, -0.02, -0.27),
x=c(1.50, 0.53, 0.04, -2.43, -0.54))
obj$data <- newdatatrain
res <- eval(obj)
return(res)
}
fun1(lm(y ~ x, data=datatrain))
# Does run through, but is not
# practical, because lm(y ~ x, data=datatrain)
# should be a function argument:
fun2 <- function(mycall) {
obj <- quote(lm(y ~ x, data=datatrain))
newdatatrain <- data.frame(y=c(0.22, 1.09, 0.93, -0.02, -0.27),
x=c(1.50, 0.53, 0.04, -2.43, -0.54))
obj$data <- newdatatrain
res <- eval(obj)
return(res)
}
fun2(lm(y ~ x, data=datatrain))
如何解决这个问题?
I would like to pass an R expression to a self-written function without
evaluating it at first and then manipulate an input parameter of
the R expression in that function.
I guess, it is easier to explain with an example.
In the below example function fun1
, which should takelm(y ~ x, data=datatrain)
as an argument without
evaluating it at first, I would like to replacedatatrain
in lm(y ~ x, data=datatrain)
bynewdatatrain
within the function (to be more precise,newdatatrain
will be datatrain
with some columns
permuted within the function).
The reason why I need to provide lm(y ~ x, data=datatrain)
as a function argument is that the function should
also be able to take other types of models with possibly other
input parameters (e.g.,randomForest::randomForest(y ~ x, data=datatrain, replace=FALSE)
).
Here is what I tried:
# Does not run through:
fun1 <- function(mycall) {
obj <- quote(mycall)
newdatatrain <- data.frame(y=c(0.22, 1.09, 0.93, -0.02, -0.27),
x=c(1.50, 0.53, 0.04, -2.43, -0.54))
obj$data <- newdatatrain
res <- eval(obj)
return(res)
}
fun1(lm(y ~ x, data=datatrain))
# Does run through, but is not
# practical, because lm(y ~ x, data=datatrain)
# should be a function argument:
fun2 <- function(mycall) {
obj <- quote(lm(y ~ x, data=datatrain))
newdatatrain <- data.frame(y=c(0.22, 1.09, 0.93, -0.02, -0.27),
x=c(1.50, 0.53, 0.04, -2.43, -0.54))
obj$data <- newdatatrain
res <- eval(obj)
return(res)
}
fun2(lm(y ~ x, data=datatrain))
How could this be tackled?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我误解了,我很抱歉,但是你能不能做这样的事情:
I'm sorry if I misunderstood, but can you not do something like this: