3

I'm looking for a clean way to run simulations where each iteration depends on the result of the preceding iteration in a "functional style." For example, say we want to take a normally distributed sample of size 10 with mean meanInit, take the mean of our sample and use that to generate another sample, and repeat the process. Using Reduce, we can perform 100 iterations:

meanInit = 0
nextStep <- function(param, step) mean(rnorm(10, param))
Reduce(nextStep, 1:100, meanInit, accumulate = T)

However, this feels a bit abusive as our function nextStep isn't truly a binary operation; indeed, we ignore the second argument step. Is there an alternative method for performing a task that doesn't require us to "pretend" our function is a binary operation? I'm looking for a solution involving higher order functions. No for loops please.

Perhaps this question is best stated in the form of an analogy:

sapply is to replicate as Reduce is to ______?

That is, if we wanted to, for example, take 100 random normal samples of size 10 and calculate the mean, we could (ab)use sapply with a function that ignores its argument as follows:

sapply(1:100, function(x) mean(rnorm(10)))

Or we could perform the same task cleanly (without writing a function that ignores its argument) using replicate:

replicate(100, mean(rnorm(10)))

I'm looking for an analogous relative of Reduce.

Richard Border
  • 3,209
  • 16
  • 30
  • 1
    `for`? Be a rebel ! – HubertL Dec 08 '16 at 23:52
  • 1
    `Reduce`'s code is full of `for()` loops by the way - there's nothing inherently wrong with a loop. – thelatemail Dec 09 '16 at 00:04
  • 2
    I've generally found that any sort of sequential processing that involves dependencies on prior values using anything other than `cumsum` or `cumprod` will run better and be less error prone using `for`-loops. – IRTFM Dec 09 '16 at 00:10
  • @thelatemail didn't say there was! I just prefer reading/writing code that avoids for loops but I know many others who feel the opposite. – Richard Border Dec 09 '16 at 01:19
  • @42 You might be right, though maybe that wouldn't be the case if there were a function to fill in the blank in my analogy above? – Richard Border Dec 09 '16 at 01:19
  • 1
    I'd suggest looking for code that has been written for solving differential equations and especially the code involving stochastic differential equations. – IRTFM Dec 09 '16 at 01:31

0 Answers0