laurelisse laurelisse - 1 year ago 84
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){



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

ex<- function(x){

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


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

So I would like to be able to write
and get the value 2.0001.

Thanks in advance!

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download