I am trying to use a variable that stores a function name as a character string to draw a curve. Something like the following:
f1 <- function(x) 0*x
f2 <- function(x) 1 + 0*x
f3 <- function(x) 2 + 0*x
fn <- "f1"
plot.new()
plot.window(xlim = c(0, 1), ylim = c(-1, 3))
curve(get(fn), add = TRUE)
Error in curve(get(fn), add = TRUE) :
'expr' must be a function, or a call or an expression containing 'x'
curve(f1, add = TRUE)
curve(f2, add = TRUE)
curve(f3, add = TRUE)
I know I am missing something with how curve
handles the expressions with substitute, or how get
is passing the function. I am particularly confused because class(get(fn))
returns "function".
Well, the issue is that curve()
doesn't evaluate the parameter you pass in. It looks at what you passed in to the parameter, not the results of evaluating the parameter. When you run
curve(fn)
what you're passing in is a "name" (or "symbol"). That triggers the function to find the function with that name. When you run
curve(get("f1")) #error
you've passed in a call. Again, that call isn't executed by curve to see that it returns a function. As the error message says, if you pass in a call, that expression should contain x
. For example
curve(f1(x))
is an example of the call syntax with the x
variable.
If you really need to specify the function as a character vector, you can convert the character to a name object and then build the call to curve with do.call. For example
do.call("curve",list(as.name(fn)))
or you can modify your call to trigger the resulting function with the special x
variable
curve(get(fn)(x))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With