Last active
April 10, 2017 13:06
-
-
Save carlislerainey/77b344e4190dda3fc26bd4b41d32751c to your computer and use it in GitHub Desktop.
code to repeat a box model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# box model | |
box <- c(0, 1) # the box | |
N <- 10 # the number of draws to take from the box | |
n_reps <- 10000 # the number of times to take and sum N draws from the box | |
# create a function to take and sum N draws from the box n_reps times | |
box_model <- function(box, N, n_reps) { | |
sums <- numeric(n_reps) | |
for (i in 1:n_reps) { | |
draws <- sample(box, size = N, replace = TRUE) # take N draws with replacement | |
sums[i] <- sum(draws) # sum (and store) the sum of the N draws | |
} | |
# print results | |
box_SD <- sqrt(mean((box - mean(box))^2)) | |
cat(paste0("The expected value of the sum is ", round(N*mean(box), 1), ".\n")) | |
cat(paste0("The SE of the sum is ", round(sqrt(N)*box_SD, 1), ".\n")) | |
cat(paste0("The observed average of the ", n_reps, " sums is ", round(mean(sums), 1), ".\n")) | |
cat(paste0("The observed SD of the ", n_reps, " sums is ", round(sqrt(mean((sums - mean(sums))^2)), 1), ".\n")) | |
return(sums) | |
} | |
# n_reps times, take N draws and sum them, resulting in n_reps sums; | |
# or n_reps repetitions of the box model | |
sums <- box_model(box = box, N = N, n_reps = n_reps) | |
# comparing the histogram of the box to the histogram of the sums | |
library(ggplot2) | |
qplot(box) | |
qplot(sums) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment