title: Complex function that iterates mvrnorm over rows of a data frame
body: <p>I have data that looks like this:</p>
  <pre><code>data = data.frame(a.coef = c(.14, .15, .16), 
                    b.coef = c(.4, .5, .6), 
                    a.var = c(0.0937, 0.0934, 0.0945), 
                    b.var = c(0.00453, 0.00564, 0.00624), 
                    ab.cov = c(0.000747, 0.000747, 0.000747))
  </code></pre>
  <p>and I would like to run the following code (source: <a href="http://www.quantpsy.org/medmc/medmc.htm" rel="nofollow noreferrer">http://www.quantpsy.org/medmc/medmc.htm</a>) on each row of the data set.</p>
  <pre><code>require(MASS)
  a = data$a.coef
  b = data$b.coef
  rep = 10000
  conf = 95
  pest = c(a, b)
  acov &lt;- matrix(c(data$a.var, data$ab.cov, 
                   data$ab.cov, data$b.var), 2, 2)
  mcmc &lt;- mvrnorm(rep, pest, acov, empirical = FALSE)
  ab &lt;- mcmc[ , 1] * mcmc[ , 2]
  low = (1 - conf / 100) / 2
  upp = ((1 - conf / 100) / 2) + (conf / 100)
  LL = quantile(ab, low)
  UL = quantile(ab, upp)
  LL4 = format(LL, digits = 4)
  UL4 = format(UL, digits = 4)
  </code></pre>
  <p>I've created a relatively simple function that takes the data and the row number as inputs:</p>
  <pre><code>MCMAM &lt;- function(data_input, row_number) {
    data = data_input[row_number, ]
    a = data[[&quot;a.coef&quot;]]
    b = data[[&quot;b.coef&quot;]]
    rep = 10000
    conf = 95
    pest = c(a, b)
    acov &lt;- matrix(c(data[[&quot;a.var&quot;]], data[[&quot;ab.cov&quot;]], 
                     data[[&quot;ab.cov&quot;]], data[[&quot;b.var&quot;]]), 2, 2)
    require(MASS)
    mcmc &lt;- mvrnorm(rep, pest, acov, empirical = FALSE)
    ab &lt;- mcmc[, 1] * mcmc[, 2]
    low = (1 - conf / 100) / 2
    upp = ((1 - conf / 100) / 2) + (conf / 100)
    LL = quantile(ab, low)
    UL = quantile(ab, upp)
    return(c(LL, UL))
  }
  
  MCMAM(data, 1)
  
      2.5%      97.5% 
  -0.1901272  0.3104614 
  </code></pre>
  <p>But it would be great if there was a way to get rid of the row specification and just have the function run through the data set row by row and save the output to a new column in the data set.</p>
  <p>I've been experimenting with for loops and apply functions but haven't had any success, largely because both the matrix() and mvrnorm() functions take values rather than vectors.</p>