Search code examples
rfunctionobjectderivative

Transform a "call" object into a function in R


From a derivation I get a "call" object as seen in the code snippet. I want to transform this into a function with arguments but I can't figure out how to get it right. It returns just the call object.

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

Solution

  • alist quotes its arguments, so when you pass names of variables, their values aren't substituted in the returned list. This means that alist(a =, x =, someDeriv) is not equivalent to 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
    

    Your function fn is actually defined as:

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

    No matter what values you pass for a and x, fn returns the value of someDeriv, which in your global environment is the call a * (2 * x) + 1.

    To get the behaviour you want, you can do this:

    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