quick code snippet to create (weighted) quantiles in R
using data.table
.
library(data.table)
library(Hmisc)
# create data.table
n <- 100000
dt <- data.table(pop=runif(n), income=runif(n))
dt$group <- c(rep('A', n/2), rep('B', n/2))
dt$year <- sample(2000:2005, n, replace = T)
dt[, decile := cut(x = income,
breaks = quantile(pop, probs = 0:10/10),
labels = FALSE, include.lowest = TRUE),
by = .(year, group) ]
dt[, decile_w := cut(x = income,
breaks = Hmisc::wtd.quantile(x = income, weights=pop, probs=0:10/10,
type=c('quantile','(i-1)/(n-1)','i/(n+1)','i/n'),
normwt=FALSE, na.rm=T),
labels = FALSE, include.lowest = TRUE),
by = .(year, group) ]