Personal code snippets of @tmasjc

Site powered by Hugo + Blogdown

Image by Mads Schmidt Rasmussen from unsplash.com

Minimal Bootstrap Theme by Zachary Betz

Random Grouping by Int Division

Jun 12, 2018 #math

One way to assign a random grouping is to perform modulo operation.

library(dplyr)
library(ggplot2)

# Generate N numbers
randnums <- function(n, min = 0, max = 10000){
    sample(x = c(min:max), size = n, replace = FALSE)
}
nums <- randnums(1000)

# Find int division
mods <- nums %% 3

# Check groupings
table(mods)
## mods
##   0   1   2 
## 302 345 353
# Repeat many times
reps <- purrr::map(1:2000, ~table(randnums(1000) %% 3))

reps %>% 
    unlist() %>% 
    bind_cols(mod = rep(c(0, 1, 2), 2000), val = .) %>% 
    ggplot(aes(val, fill = factor(mod))) + 
    geom_density(alpha = 0.7) +
    labs(x = "", y = "", fill = "Remainder") +
    theme_minimal()