laurelisse laurelisse - 15 days ago 6
R Question

Function of x as input in function argument

I have written a function to approximate a derivate in a point x in R like this:

nderiv<- function(f,x,h){

(f(x+h)-f(x))/h

}


And want to make an input in f as either x^2, "x^2" or as a predefined function like:

ex<- function(x){
x^2
}


The code works fine if you use the last example (using a predefined function). But I can't get it to work when inserting the other options.

I either get the error


Error in nderiv(x^2, 1) : object 'x' not found


or


Error in nderiv("x^2", 1, 1e-04) : could not find function "f"


So I would like to be able to write
nderiv(x^2,1,0.0001)
or
nderiv("x^2",1,0.0001)
and get the value 2.0001.

Thanks in advance!

Answer

If you want to use x^2 as an anonymous function, pass it to nderiv as function(x){x^2}. Something like:

nderiv(function(x){x^2}, 1, 0.0001)
Comments