Search code examples
rfunctionderivative

Evaluation of one input in a function with multiple inputs in R


I am trying to do the following but can't figure it out. Could someone please help me?

f <- expression(x^3+4*y)
df <- D(f,'x')

x <-0
df0 <- eval(df)

df0 should be a function of y!


Solution

  • If you take the derivative of f with respect to x you get 3 * x^2. The 4*y is a constant as far as x is concerned. So you don't have a function of y as such, your df is a constant as far as y is concerned (although it is a function of x).

    Assigning to x doesn't change df; it remains the expression 3 * x^2 and is still a function of x if you wanted to treat it as such.

    If you want to substitute a variable in an expression, then substitute() is what you are looking for.

    > substitute(3 * x^2, list(x = 0))
    3 * 0^2
    

    It is a blind substitute with no simplification of the expression--we probably expected zero here, but we get zero times 3--but that is what you get.

    Unfortunately, substituting in an expression you have in a variable is a bit cumbersome, since substitute() thinks its first argument is the verbatim expression, so you get

    > substitute(df, list(x = 0))
    df
    

    The expression is df, there is no x in that so nothing is substituted, and you just get df back.

    You can get around that with two substitutions and an eval:

    > df0 <- eval(
    +   substitute(substitute(expr, list(x = 0)), 
    +             list(expr = df)))
    > df0
    3 * 0^2
    > eval(df0)
    [1] 0
    

    The outermost substitute() puts the value of df into expr, so you get the right expression there, and the inner substitute() changes the value of x.

    There are nicer functions for manipulating expressions in the Tidyverse, but I don't remember them off the top of my head.