Pass expression as variable to curve

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 that I am missing something with how curve processes expressions with substitution or how get passes a function. I am particularly confused because class(get(fn)) returns a "function".

+6
source share
1 answer

Well, the problem is that curve() does not evaluate the parameter you pass. It looks at what you passed to the parameter, not the results of evaluating the parameter. When you run

 curve(fn) 

what you are going through is a β€œname” (or β€œsymbol”). This forces the function to find a function with this name. When you run

 curve(get("f1")) #error 

You transferred the call. Again, this call is not made by a curve to see that it returns a function. As the error message says, if you pass the call, this expression should contain x . for instance

 curve(f1(x)) 

is an example of the syntax of a call with the variable x .

If you really need to specify the function as a character vector, you can convert the character to a name object, and then construct a curve call using do.call. for instance

 do.call("curve",list(as.name(fn))) 

or you can change your call to call the resulting function using the special variable x

 curve(get(fn)(x)) 
+8
source

Source: https://habr.com/ru/post/981999/


All Articles