Last active
May 28, 2021 03:33
-
-
Save audhiaprilliant/9546ad98b95a173249895c02937e6a58 to your computer and use it in GitHub Desktop.
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
| # ---------- Law of Large Number ---------- | |
| # Install packages | |
| install.packages('ggplot2') | |
| library(ggplot2) | |
| # Parameters | |
| sample_mean = 100000 | |
| sample_size = 20 | |
| set.seed(1234) | |
| # Uniform Distribution | |
| x = runif(n = 4000, min = 0, max = 1) | |
| hist(x) | |
| mean(x) | |
| sd(x) | |
| # Resampling | |
| dist = replicate(n = sample_mean, | |
| expr = mean(sample(x = x, | |
| size = sample_size, | |
| replace = TRUE))) | |
| hist(dist) | |
| mean(dist) | |
| sd(dist) | |
| sd(x) / sqrt(sample_size) # Proven | |
| # Means | |
| mean(x) | |
| means = cumsum(dist)/(1:sample_mean) | |
| # Data viz | |
| ggplot(data = data.frame(x = 1:sample_mean, | |
| y = means))+ | |
| geom_line(aes(x = x, | |
| y = y), | |
| color = 'red', | |
| size = 1.5)+ | |
| geom_hline(yintercept = mean(x))+ | |
| labs(x = 'Number of observations', | |
| y = 'Cumulative mean')+ | |
| theme_minimal() | |
| # Variance | |
| sd(x) | |
| stdev = replicate(n = sample_mean, | |
| expr = sd(sample(x = x, | |
| size = sample_size, | |
| replace = TRUE))) | |
| mean(stdev) | |
| variance = cumsum(stdev ^ 2)/(1:sample_mean) | |
| # Data viz | |
| ggplot(data = data.frame(x = 1:sample_mean, | |
| y = variance))+ | |
| geom_line(aes(x = x, | |
| y = y), | |
| color = 'red', | |
| size = 1.5)+ | |
| geom_hline(yintercept = mean(variance))+ | |
| labs(x = 'Number of observations', | |
| y = 'Cumulative variance')+ | |
| theme_minimal() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment