Skip to content

Instantly share code, notes, and snippets.

@mark-andrews
Created November 9, 2020 17:15
Show Gist options
  • Save mark-andrews/08a9d6850c9d821b32306ff85bc15ac2 to your computer and use it in GitHub Desktop.
Save mark-andrews/08a9d6850c9d821b32306ff85bc15ac2 to your computer and use it in GitHub Desktop.
library(tidyverse)
theme_set(theme_classic())
plot_normal <- function(mean = 0, sd = 1, xmin = -3, xmax = 3) {
tibble(x = seq(xmin, xmax, length.out = 1000),
d = dnorm(x, mean = mean, sd = sd)) %>%
ggplot(aes(x = x, y = d)) + geom_line() +
geom_segment(x = mean,
xend = mean,
y = 0,
yend = dnorm(mean, mean, sd), colour = 'grey') +
geom_segment(x = mean,
xend = mean + sd,
y = dnorm(mean, mean, sd)/2,
yend = dnorm(mean, mean, sd)/2, colour = 'grey')
}
normal_percentiles <- function(mean = 0, sd = 1){
c(`0.005` = qnorm(0.005, mean = mean, sd = sd),
`0.025` = qnorm(0.025, mean = mean, sd = sd),
`0.25` = qnorm(0.25, mean = mean, sd = sd),
`0.5` = qnorm(0.5, mean = mean, sd = sd),
`0.75` = qnorm(0.75, mean = mean, sd = sd),
`0.975` = qnorm(0.975, mean = mean, sd = sd),
`0.995` = qnorm(0.995, mean = mean, sd = sd))
}
plot_normal_sample <- function(n = 1000, mean = 0, sd = 1, bins = 10){
tibble(x = rnorm(n, mean, sd)) %>%
ggplot(aes(x = x)) + geom_histogram(bins = bins, colour = 'white')
}
plot_repeat_normal_samples <- function(N = 1000, n = 10, mean = 0, sd = 1){
df <- map(seq(N),
~rnorm(n, mean = mean, sd = sd) %>%
enframe() %>%
summarize(mean = mean(value), stdev = sd(value))
) %>% bind_rows() %>%
rownames_to_column(var = 'id') %>%
mutate(id = as.numeric(id))
ggplot(df,
aes(x = id, y = mean)) +
geom_point() +
geom_hline(yintercept = mean, colour = 'red') +
ylim(mean - sd * 2, mean + sd * 2)
}
hist_repeat_normal_samples <- function(N = 1000, n = 10, mean = 0, sd = 1, bins = 25){
df <- map(seq(N),
~rnorm(n, mean = mean, sd = sd) %>%
enframe() %>%
summarize(mean = mean(value), stdev = sd(value))
) %>% bind_rows() %>%
rownames_to_column(var = 'id') %>%
mutate(id = as.numeric(id))
ggplot(df,
aes(x = mean)) +
geom_histogram(bins = bins, colour = 'white')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment