Created
May 16, 2024 16:35
-
-
Save battenr/e6613fbe6f17060174c92dfda1b0d185 to your computer and use it in GitHub Desktop.
Demonstrating Standard Error
This file contains hidden or 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
| # Title: Demonstration of Standard Error | |
| # Description: The purpose of this script is to demonstrate standard error. | |
| # A sample is repeatedly drawn then the mean is calculated. The result, each | |
| # sample mean is then plotted | |
| # Setup ---- | |
| library(tidyverse) # ol faithful | |
| # Generating Data ---- | |
| set.seed(123) # for reproducibility | |
| population <- rnorm(10000, mean = 50, sd = 10) # a normal distribution with mean = 50 and sd = 10 | |
| # Draw samples and calculate their means | |
| sample_size <- 500 # size of each sample | |
| num_samples <- 1000 # number of samples to draw | |
| # Repeatedly sampling then calculating the mean | |
| sample_means <- replicate(num_samples, mean(sample(population, sample_size))) | |
| # Calculating the standard error ---- | |
| # Calculating the standard error. This is the standard deviation of the sampling distribution | |
| # in this case the statistic is the mean, so standard deviation of the means. | |
| se_sample_means <- sd(sample_means) | |
| # Plotting Results ---- | |
| # Plot the distribution of sample means | |
| ggplot(data.frame(sample_means), aes(x = sample_means)) + | |
| geom_histogram(bins = 30, color = "black", fill = "blue", alpha = 0.7) + | |
| # Adding titles | |
| labs(title = " Sampling Distribution", | |
| subtitle = paste("N = 500, Sample Drawn 1000 Times, SE =", round(se_sample_means, 2)), | |
| x = "Sample Mean", | |
| y = "Frequency") + | |
| theme_minimal() + # changing to minimal theme | |
| # Setting y scale | |
| scale_y_continuous(limits = c(0, 120), | |
| breaks = c(0, 20, 40, 60, 80, 100, 120)) + | |
| # Centering title and increasing font size | |
| theme( | |
| text = element_text(size = 14), | |
| plot.title = element_text(hjust = 0.5), | |
| plot.subtitle = element_text(hjust = 0.5) | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment