Skip to content

Instantly share code, notes, and snippets.

@dawaldron
Created July 3, 2019 04:35
Show Gist options
  • Save dawaldron/c5bf89c6d3418ce7ead04f758c99766e to your computer and use it in GitHub Desktop.
Save dawaldron/c5bf89c6d3418ce7ead04f758c99766e to your computer and use it in GitHub Desktop.
library(data.table)
library(magrittr)
dt <- fread('meps_00004.csv')
# rename monthly insurance indicators to be sortable
setnames(dt,
c('INSJAX','INSFEX','INSMAX','INSAPX','INSMYX','INSJUX',
'INSJLX','INSAUX','INSSEX','INSOCX','INSNOX','INSDEX'),
sprintf('%02d',1:12))
# pivot monthly insurance indicators
dt <- melt(dt,
id.vars = c('YEAR','MEPSID','PERWEIGHT','AGE'),
measure.vars = sprintf('%02d',1:12),
variable.name = 'MONTH',
value.name = 'INS',
value.factor = FALSE)
# exclude 'not in universe'
dt <- dt[INS != 0]
# count months of data for each person, year
dt[,
MONTHS := .N,
.(MEPSID, YEAR)]
# for people under age 65 with 12 months of data
# in a year, count months insured
dt_sum <- dt[AGE < 65 & MONTHS == 12,
.(MONTHSINS = sum(INS == 2),
PERWEIGHT = mean(PERWEIGHT)),
.(MEPSID, YEAR)] %>%
.[,
.(EST = sum(PERWEIGHT)),
.(YEAR, MONTHSINS)] %>%
.[, PCT := round(100 * EST / sum(EST), 1), .(YEAR)] %>%
dcast(YEAR ~ MONTHSINS, value.var = 'PCT')
fwrite(dt_sum, 'meps_months_insured.csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment