Do something then append that value do an empty vector

Viewed 28

I have written a function that draws random variates from a normal distribution with outliers. However I now want to take the mean of this data and append it to an empty vector 1000 times (so essentially a vector with 1000 different means using my function) Here is my attempt so so far.

M = 1000
for (i in 1:M){
  means = numeric()
  m = mean(rnormout(100,0,1,0,10))
  means[i] = m[i]
}

However I just seem to get 1000 NAs in my means vector, any suggestions? Thanks!

2 Answers

There are a few ways of doing this. If you want to use a loop, the trick is to define an empty vector before initiating the loop, and store values in that. Here's an example using rnorm to generate values from a standard normal, since I don't have the code for your rnormout function:

M <- 1000
means <- vector()
for (i in 1:M){
  means[i] = mean(rnorm(100, 0, 1))
}

Alternatively, it's better not to use a for loop at all. You can use map_dbl to replace the loop in one line:

library(tidyverse)
M <- 1000
means <- map_dbl(1:M, ~ mean(rnorm(100, 0, 1)))

We could use sapply in base R (use R 4.1.0)

M <- 1000
sapply(seq_len(M), \(x) mean(rnorm(100, 0, 1)))
Related