Skip to content

Instantly share code, notes, and snippets.

@affans
Created April 16, 2021 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save affans/23fa08cd00c0f6211203dd77e05a3d72 to your computer and use it in GitHub Desktop.
Save affans/23fa08cd00c0f6211203dd77e05a3d72 to your computer and use it in GitHub Desktop.
function get_agedist(st)
grps = (0:4, 5:16, 17:49, 50:65, 66:99)
_data = CSV.File("sc-est2019.csv") |> DataFrame!
# select only the relevant columns
select!(_data, Not(8:17))
# filter to include both male/female, state
filter!(r -> r[:SEX] == 0 && r[:NAME] == st && r[:AGE] <= 99, _data)
# calculate the the age groups
transform!(_data, :AGE => ByRow(x -> findfirst(grp -> x in grp, grps)) => :AGEGRP)
# group by
gdf = groupby(_data, :AGEGRP)
combine(gdf, :POPEST2019_CIV => sum)
end
# test
get_agedist("Connecticut")
# 5×2 DataFrame
# Row │ AGEGRP POPEST2019_CIV_sum
# │ Int64 Int64
# ─────┼────────────────────────────
# 1 │ 1 181710
# 2 │ 2 499697
# 3 │ 3 1481961
# 4 │ 4 808133
# 5 │ 5 586881
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment