mercredi 13 septembre 2017

Stratified random sampling in R after merging

Say we have an original dataset that includes the population, and we have a merged dataset that includes the population after being merged with another dataset (thus less observations).

library(tidyverse)
set.seed(0)

population_data <- data.frame(ID = c(1:100),
                     industry = sample(1:10, 100, replace = T),
                     size = log1p(runif(100, 1e+03, 1e+08)),
                     performance = runif(100, -0.10, 0.10))

merged_data <- population_data[sample(nrow(population_data), 50), ]

From this 'merged' dataset, I would like to take a stratisfied random sample based on certain characteristics of the original population dataset on, for example, industry level.

population_characteristics <- population_data %>% 
  group_by(industry) %>% 
  summarize(avg_industry_size = n() / nrow(population_data),
            avg_size = mean(size, na.rm = T),
            avg_performance = mean(performance, na.rm = T))

What would be the easiest way to take a sample of 20 observations of the 'merged_data' object such that the characteristics of this new sample match as closely as possible with those in the 'population_characteristics', after grouped by industry again?




Aucun commentaire:

Enregistrer un commentaire