upman upman - 5 months ago 29
R Question

Using a function as an argument of another function and execute it in each loop

I have several functions in R that get me vectors with different random results, let's call these functions r1, r2, r3 and r4.

Now I want to write another function named 'simulation' that simulates one of these functions above and evaluates different values like the expected value etc.
Furthermore, I want only one function that can simulate either r1, r2, r3 or r4, which is possible, because they all put out the same type of vector.

I have tried it by the following way:

simulation <- function(f, n) {
result <- 0
for (i in 1:n) {
result <- result + f[1]

Then I execute it like this:
simulation(r1(), 500)

This works fine, but the problem is that the function r1() just runs once, but as I want to simulate it n times, I want it to run each time I go through the for-loop.

Is there any way I can do this?

Thanks in advance!


You can pass the function itself instead of its return value :

simulation(r1, 500)

But then you have to modify the code :

result <- result + f()[1]