将 "call" 对象转换为 R 中的函数

Transform a "call" object into a function in R

从推导中,我得到了一个“调用”对象,如代码片段中所示。我想将其转换为带参数的函数,但我不知道如何正确处理。它returns只是调用对象。

someDeriv <- D(expression(a * x^2 + x), "x")
someDeriv
#returns: a * (2 * x) + 1
class(someDeriv)
#returns: "call"

#here comes the important part
fn <- as.function(alist(a=,x=,someDeriv))

fn(a=1, x=2)
#returns: a * (2 * x) + 1
#should return: 5

alist 引用其参数,因此当您传递变量名称时,它们的值不会在返回的列表中被替换。这意味着 alist(a =, x =, someDeriv) 等同于 alist(a =, x =, a * (2 * x) + 1).

someDeriv <- D(expression(a * x^2 + x), "x")
l1 <- alist(a =, x =, someDeriv)
l1
$a


$x


[[3]]
someDeriv
l2 <- alist(a =, x =, a + (2 * x) + 1)
l2
$a


$x


[[3]]
a + (2 * x) + 1

你的函数fn实际定义为:

fn <- as.function(l1)
fn
function (a, x) 
someDeriv

无论您为 ax 传递什么值,fn returns someDeriv 的值在您的全局环境中是呼叫 a * (2 * x) + 1.

要获得您想要的行为,您可以这样做:

l3 <- c(alist(a =, x =), list(someDeriv))
l3
$a


$x


[[3]]
a * (2 * x) + 1
fn <- as.function(l3)
fn(a = 1, x = 2)
[1] 5