How to pass a function as an argument to another function in R?

Consider the following example:

q1.func <- function(x) { num <- (cos(30.2 * x^(1/2)))^2 denom <- (x^0.7) * exp(0.9*x) num / denom } method1 <- function(n) { x <- runif(n,min = 0, max = 1.7) f <- q1.func(x) (1.7) * sum((1/n) * f) } draw.graph <- function() { n <- seq(1,1000,1) x <- c() for(i in 1:length(n)) { x <- append(x, method1(n[i])) } plot(n, x, type = "p", xlab = "N",ylab = "value" ,main = "method1 plot",col = "black") } 

I want to say that I want to execute: draw.graph (method1 (n)) . But R would not let me do this. I do not understand why this is happening ??? My ultimate goal is that I could pass method2 / method3 / .... as an argument to the draw.graph () function. But how??? Now I'm only interested in solutions that allow me to pass method1 as an argument to the draw.graph function. Please do not ask me to write method1 in the draw.graph function, because I already know that it works. But I'm more interested in passing method1 as an argument to the draw.graph function. Thanks

+4
source share
2 answers

I will give a simpler example to illustrate the main question (there are other problems with the code you proposed).

 fun1 = function(x) cos(x) fun2 = function(x) sin(x) # function where one argument is a function wrapper = function(a = 2, fun = fun1){ x = 1:10 return(data.frame(x = x, y = a*fun(x))) } # testing behaviour wrapper() wrapper(fun = fun2) 
+5
source

Your draw.graph function draw.graph missing an argument. Why not just use the return value of the function as an argument to the next function?

 draw.graph <- function(y) { plot(seq_along(y), y) } method1 <- function(n) { return(runif(n, min=0, max=1.7)) } draw.graph(method1(100)) 

If you really need a function as an argument, you can try the following (please read ?match.fun ):

 ## stupid example calc <- function(x, fun) { fun <- match.fun(fun) return(fun(x)) } calc(1:10, sum) 

EDIT: To fulfill the OP question / comments, I add this specific example:

 q1.func <- function(x) { num <- cos(30.2 * sqrt(x))^2 denom <- x^0.7 * exp(0.9*x) return(num/denom) } method1 <- function(n) { x <- runif(n, min=0, max=1.7) return(1.7*sum(1/n*q1.func(x))) } draw.graph <- function(n, fun) { fun <- match.fun(fun) y <- unlist(lapply(n, fun)) plot(n, y) } draw.graph(1:1000, method1) 

enter image description here

+5
source

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


All Articles