library(ipumsr)
library(readr)
library(survey)
library(dplyr)
library(matrixStats)
library(writexl)Household Income - All Members on Medicaid
ddi <- read_ipums_ddi("usa_00050.xml")
acs_data <- read_ipums_micro(ddi, data_file = "usa_00050.dat", verbose = FALSE)#create person-level flags
acs_data <- acs_data %>%
mutate(
is_head = RELATE == 1,
is_spouse = RELATE == 2,
is_elderly = AGE >= 65,
is_child = AGE < 18,
is_female_head = is_head & SEX == 2,
has_medicaid_person = HINSCAID == 2,
has_foodstamps_person = FOODSTMP == 2
)#collapse to household-level
hh_summary <- acs_data %>%
group_by(SERIAL) %>%
summarise(
fam_sz = first(FAMSIZE),
hh_income = first(HHINCOME),
hh_weight = first(HHWT),
num_parents = sum(is_head | is_spouse),
num_children = sum(is_child),
num_elderly = sum(is_elderly),
female_head = any(is_female_head),
all_medicaid = all(has_medicaid_person),
all_foodstamps = all(has_foodstamps_person)
)
#filter for households with children and elderly on Medicaid and Food Stamps
hh_summary <- hh_summary %>%
filter(all_medicaid & all_foodstamps,
!is.na(hh_income) & hh_income >= 0 & hh_income != 9999999)#classify household types
hh_summary <- hh_summary %>%
mutate(
household_type = case_when(
num_parents == 1 & female_head & num_children == 1 & num_elderly == 0 & fam_sz == 2 ~ "Single Mother + Child",
num_parents == 1 & num_children == 1 & num_elderly == 0 & fam_sz == 2 ~ "Single Parent + Child",
num_parents == 2 & num_children == 1 & num_elderly == 1 & fam_sz == 4 ~ "Two Parents + Child + Elderly",
num_parents == 1 & num_children == 1 & num_elderly == 1 & fam_sz == 3 ~ "Single Parent + Child + Elderly",
TRUE ~ "Other"
)
)#calculate weighted median income by household type
weighted_median_income <- hh_summary %>%
group_by(household_type) %>%
summarise(
weighted_median_income = weightedMedian(hh_income, w = hh_weight, na.rm = TRUE),
.groups = "drop"
)
print(weighted_median_income)# A tibble: 5 × 2
household_type weighted_median_income
<chr> <dbl>
1 Other 14500
2 Single Mother + Child 19467.
3 Single Parent + Child 18018.
4 Single Parent + Child + Elderly 24512.
5 Two Parents + Child + Elderly 52707.
#save to Excel
write_xlsx(weighted_median_income, "hh_income_medicaid_snap_famsize.xlsx")