Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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")
}

My point is that I want to be able to perform: draw.graph(method1(n)). But R wouldnt allow me to do that. I dont understand why is this happening??? My ultimate goal is that I would be able to pass method2 / method3 /.... as argument of draw.graph() function. But how??? Right now, I am only interested in solutions that allow me to pass method1 as an argument of the draw.graph function. Please dont ask me to write method1 WITHIN the draw.graph function, because I already know that it works. But I am more interested in passing method1 as an argument of the draw.graph function. Thanks

like image 436
mynameisJEFF Avatar asked Dec 27 '22 14:12

mynameisJEFF


1 Answers

I'll make a simpler example to illustrate the main point (there are other issues 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)
like image 143
baptiste Avatar answered Mar 15 '23 23:03

baptiste