Chris Lagree
Chris Lagree

Reputation: 13

For Loop in R. How can I save the outputs?

I am trying to save each value from this for loop into a vector:

for (i in 1:10000){
  mean((rbinom(1000,5,0.7)))
}

But I have not been successful in doing so.

I know I need to create the vector before the loop and call it inside it, but I'm not sure how to go about it.

Upvotes: 1

Views: 832

Answers (1)

RHertel
RHertel

Reputation: 23818

Without using a for loop, you could do something like:

means.vec <- replicate(10000, mean(rbinom(1000,5,0.7)))

If you really need a for loop, you can try:

means.vec <- vector()
for (i in 1:10000) {
   means.vec[i] <- mean(rbinom(1000,5,0.7))
}

Upvotes: 1

Related Questions