0

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]
  }
  result
}

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!

0

1 Answer 1

3

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, did not expect that it would be that easy. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.