library(tidycensus) library(zipcodeR) #Pull the relevant median age variables the value moe (margine of error) can be converted to standard error, following the link below #https://www.census.gov/content/dam/Census/library/publications/2018/acs/acs_general_handbook_2018_ch08.pdf ACS_YEAR <- 2023 #most recent as of Nov 4 2025 source("Scripts/Downshift_Population_Functions.r") #Packages to instal on computer if zipcodeR won't install #Sudo apt install libssl-dev libudunits2-dev libabsl-dev libcurl4-openssl-dev libgdal-dev cmake libfontconfig1-dev libharfbuzz-dev libfribidi-dev #install.packages("zipcodeR") #Add API key if missing #KEY <- '30e13ab22563318ff59286e433099f4174d4edd4' #census_api_key(KEY, install = TRUE) PROJ_TRACTS <- get_tracts(search_city('Kemmerer','WY')$zipcode) %>% full_join(get_tracts(search_city('Diamondville','WY')$zipcode)) PROJ_TRACTS <- PROJ_TRACTS %>% select(GEOID) %>% mutate('IN_KEM'=1) %>% mutate(GEOID=as.character(GEOID)) MED_AGE_VAR <- cbind(c('B01002_001E','B01002_002E','B01002_003E'),c('Median_Age','Median_Age_Male','Median_Age_Female')) %>% as_tibble %>% rename(variable=V1,Data_Type=V2) ###Load data manually created which links vairable names to sex-age census data CODES <- read_csv("Data/API_CENSUS_CODES.csv",skip=1) %>% mutate(Med_Age=(Min_Age+Max_Age)/2) %>% rename(variable=Code) #Testing age Comparison between the two ###Extract census data for all tracts in Lincoln county, clean up the data, and indicate if the tract is in Kemmerer/Diamondvile or not. AGE_DATA <- get_acs(geography="tract",year=ACS_YEAR,variables=CODES$variable,state='WY',county='lincoln') %>% mutate(se=moe/1.64) %>% left_join(CODES %>% mutate(variable=gsub('E','',variable))) %>% select(-NAME,-moe) %>% left_join(PROJ_TRACTS) %>% mutate(IN_KEM=ifelse(is.na(IN_KEM),0,1)) %>% rename(Population=estimate) %>% select(-variable,-GEOID) %>% select(Sex,Min_Age,Max_Age,Med_Age,IN_KEM,Population,se) %>% filter(!(Min_Age==0& Max_Age==Inf)) AGE_DATA <- AGE_DATA %>% group_by(Sex,Min_Age,Max_Age,Med_Age,IN_KEM)%>% summarize(Population=sum(Population)) %>% ungroup #Add Descriptive age category to a clean graph AGE_DATA$Ages <- paste(AGE_DATA$Min_Age,"to",AGE_DATA$Max_Age) AGE_DATA[AGE_DATA$Max_Age==Inf,"Ages"] <- "85+" AGE_DATA[AGE_DATA$Med_Age==18,"Ages"] <- "18" AGE_DATA[AGE_DATA$Med_Age==20,"Ages"] <- "20" AGE_DATA[AGE_DATA$Med_Age==21,"Ages"] <- "21" AGE_DATA[AGE_DATA$Min_Age==0,"Ages"] <- "Under 5" #Turn the ages into factors to keep the correct order in graphs #Add the percent of total relative population in the region ORD <- AGE_DATA %>% select(Min_Age,Ages) %>% unique %>% arrange(Min_Age) %>% pull(Ages) %>% unique AGE_DATA$Ages <- factor(AGE_DATA$Ages,levels=ORD) AGE_DATA$Year <- ACS_YEAR AGE_DATA <-AGE_DATA %>% select(Year,Sex,Ages,IN_KEM,everything()) if(!exists('ACS_FILE_LOC')){ACS_FILE_LOC <- "Data/Cleaned_Data/ACS_Census_Demographic_Data.Rds"} saveRDS(AGE_DATA,ACS_FILE_LOC)