Argument of a function is another function

Asked

Viewed 289 times

6

I would like to know how to put as an argument of a function another function.

For example, let’s say I want to solve an integral by a given numerical method of approximation of an integral. And I want to create a function that does that, where the arguments of the function are:

Integral = function(a,b, fx)

In which a and b are the integration intervals and fx is the role I want to integrate.


It’s not working yet. See:

trapezio.integracao <- function(a, b, fn){ fn(x) }
 {
   x = seq(a, b, by = 0.005)
   n = length(x)

   integral = 0.5*sum((x[2:n] - x[1:(n-1)]) * (f(x[2:n]) + f(x[1:(n-1)]) ) )

   return(integral)
}

fx <- function(x){x^2}

trapezio.integracao(0,1,fx)
  • If I understand what you are trying to do, you are making two mistakes there: 1 - trapezio.integracao <- function(a, b, fn){ fn(x) } this defines a function that applies the function fn to an object x that does not exist within the scope of that function 2 - the excerpt below that is what you probably want to use within the function and yet, you are not making use of the argument fn. See my updated response to better understand.

1 answer

2


Just pass the function as argument, for example:

funcaoSoma <- function(a,b){a + b}
funcaoAritmetica <- function(a, b, fn){ fn(a,b) }

When you run funcaoAritmetica(2,3,funcaoSoma), R will execute the function passed by the argument fn and return you the value 5.

EDIT:

The function you posted does not work because it makes correct use of the function as argument, the correct one would be:

trapezio.integracao <- function(a, b, fn)
 {
   x = seq(a, b, by = 0.005)
   n = length(x)

   //Aqui você irá usar a função passada como argumento,
   // pelo nome de 'fn' (o nome que está indicado na definição da função) e não 'f'

  //No seu exemplo, ficaria assim:
  integral = 0.5*sum((x[2:n] - x[1:(n-1)]) * (fn(x[2:n]) + fn(x[1:(n-1)]) ) )


   return(integral)
}

fx <- function(x){x^2}

This way, when you run, you will get the following result:

> trapezio.integracao(0,1,fx)
[1] 0.3333375
  • Still not working, see my program below. :/

  • Thank you so much! Now I understand the mistakes I made.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.