Search code examples
rrepeatstatistics-bootstrap

Repeating a process 1000 times and creating a plot


Let's start with some data:

df <- rnorm(30)

I want to randomly sample 1000 times df obtaining each time 5 numbers without repetition and calculate its coefficient of variation (cv):

sample_df <- sample(df, 5, replace = F) 
cv <- (sd(sample_df) / mean(sample_df)) * 100

So now. I would like to repeat 1000 times the two last lines of code, so I would get 1000 coefficients. How can I do it?

Later on, I would like to merge all of the coefficients and draw an histogram or a density plot.


Solution

  • We can place the codes inside a brace and use replicate

    n <- 1000
    out <- replicate(n, {sample_df <- sample(df, 5, replace = FALSE)
                   sd(sample_df)/mean(sample_df) * 100})
    hist(out)
    

    EDIT: Based on @Ben Bolker's comments