Search code examples
rsimulation

Producing different outputs when passing rnorm() as a parameter in a function


I have been trying to pass rnorm as a parameter in my function:

simpleTest <- function(x) {
  print(x)
  print(x)
}

simpleTest(rnorm(2, 0, 1))

And my goal is to get R to produce different results with the two print commands. However, this way, I get the same result for both commands. Now, I could do something like this:

simpleTest <- function() {
  print(rnorm(2, 0, 1))
  print(rnorm(2, 0, 1))
}

simpleTest()

but my goal is to put the print command in a loop and repeat the process, say, 10,000 times. Is there a way that allows me to pass rnorm as a parameter in my function, but at the same time, R is forced to produce different values each time? Thank you!


Solution

  • The standard way to do something like this is to use the inbuilt replicate() function:

    replicate(5, rnorm(2,0,1))
    #>            [,1]       [,2]        [,3]       [,4]       [,5]
    #> [1,] -0.9463522 -0.8894967 -0.01546813 -0.9255994 -0.3952985
    #> [2,]  0.5598454  1.1042825 -0.13638187 -0.6531151  0.9983296