Message-ID: <8b727e71-d41f-01e1-55b3-67836578782a@gmail.com>
Date: 2016-06-18T23:24:49Z
From: Duncan Murdoch
Subject: better loop for simulation
In-Reply-To: <CY1PR07MB25888BEDCE91D0116E2987E9FA280@CY1PR07MB2588.namprd07.prod.outlook.com>
On 18/06/2016 6:12 PM, Naresh Gurbuxani wrote:
> I want to calculate a function many times over. My solution below works, but does not seem very elegant.
>
> # my function to run many times over
> stud.score <- function(n.questions, mult.choice = 2) {
> prob.success <- 1 / mult.choice
> answers <- (runif(n.questions) < prob.success)
> return(sum(answers))
> }
>
> # my method to run above function 1000 times and store results
> count.df <- data.frame(n.count = rep(10, 1000))
> scores.df <- apply(count.df, 1, function(x) return(stud.score(x)))
>
> Creating a data frame just to repeat the the count seems wasteful. How can I generate scores.df without count.df?
>
> Thanks,
You don't need a data frame or a loop at all. You're simulating
binomial values, and R has rbinom() to do that in a vectorized way.
Duncan