
이 코드는 미국 인구조사 데이터를 활용하기 위한 API 키 설정, 필요한 패키지 설치, 데이터 가져오기, 그리고 특정 변수와 지역 데이터를 필터링 및 시각화하기 위한 작업 과정을 보여줍니다.
데이터 전처리: API 키 설정 → 변수 탐색 및 필터링 → 데이터 가져오기 및 퍼센트 계산.
| 단계 | 주요 함수/코드 |
|---|---|
| 1. API KEY | census_api_key("API_KEY", install = TRUE, overwrite = TRUE) |
| 2. D.set탐색 | load_variables(year = 2019, dataset = "acs1", cache = TRUE) |
| 3. 변수필터링 | filter(str_detect(name, "B01001._001")) |
| 4. D.가져오기 | get_acs(geography = "county", state = "FL", variable = race_variables_names, geometry = TRUE) |
| 5. % 계산 | mutate(percent = 100 * estimate / summary_est) |
| 6. D결합 | inner_join(race_variables, by = c("variable" = "name")) |
| 7. 시각화 | geom_sf(), facet_wrap(~concept_short), scale_fill_viridis_c(), theme_void() |
https://api.census.gov/data/key_signup.html
api 키 받기 + g메일주소입력!!
6b3123c92c911ef3b80640296b2de59f7b815669
install.packages("viridis")
install.packages("tidycensus")
install.packages("patchwork")
install.packages("mapview")
library(tidyverse)
library(viridisLite)
library(viridis)
library(tidycensus)
library(patchwork)
library(mapview)
census_api_key("6b3123c92c911ef3b80640296b2de59f7b815669", install = TRUE)
census_api_key("6b3123c92c911ef3b80640296b2de59f7b815669", install = TRUE, overwrite = TRUE) #원래 조교샘키..
datasets <- c("sf1", "sf2", "sf3", "sf4", "pl",
"as", "gu", "mp", "vi", "acs1", "acs3",
"acs5", "acs1/profile", "acs3/profile",
"acs5/profile", "acs1/subject",
"acs3/subject", "acs5/subject",
"acs1/cprofile", "acs5/cprofile")
acs1_variables <- load_variables(year = 2019, dataset = "acs1", cache = TRUE)
acs1_variables
race_variables <- acs1_variables |>
filter(str_detect(name, "B01001._001")) |>
mutate(concept_short = str_extract(concept, regex("(?<=\\().{11}")))
race_variables
race_variables_names <- c("B01001A_001", "B01001B_001", "B01001C_001",
"B01001D_001", "B01001E_001", "B01001I_001")
fl_races_county <- get_acs(
year = 2019,
geography = "county",
state = "FL",
variable = race_variables_names)
fl_races_county
fl_races_county_geo <- get_acs(
year = 2019,
geography = "county",
state = "FL",
variable = race_variables_names,
geometry = TRUE)
fl_races_county_geo
fl_races_county_geo <- get_acs(
state = "FL",
geography = "county",
variables = race_variables_names,
summary_var = "B01001_001",
geometry = TRUE)
fl_races_county_geo
with_race_percent <- fl_races_county_geo |>
mutate(percent = 100 * estimate / summary_est)
with_race_percent <- with_race_percent |>
inner_join(race_variables, by = c("variable" = "name"))
with_race_percent |>
ggplot(aes(fill = percent)) +
facet_wrap(~concept_short) +
geom_sf(color = NA) +
theme_void() +
scale_fill_viridis_c() +
labs(fill = "% of population\n(2019 Census)")
1. API 키 설정
census_api_key("6b3123c92c911ef3b80640296b2de59f7b815669", install = TRUE, overwrite = TRUE)
census_api_key():install = TRUE로 설정하면 키가 시스템에 저장되어 이후 세션에서도 사용 가능합니다.overwrite = TRUE는 기존에 저장된 키를 덮어씌웁니다.install.packages("viridis")
install.packages("tidycensus")
install.packages("patchwork")
install.packages("mapview")
library(tidyverse)
library(viridisLite)
library(viridis)
library(tidycensus)
library(patchwork)
library(mapview)
viridis: 색상 팔레트를 제공하며, 시각화에 사용.tidycensus: 미국 인구조사 데이터를 R에서 편리하게 가져오기 위한 패키지.patchwork: 여러 ggplot 그래프를 조합하여 하나의 시각화로 표시.mapview: 지리 데이터를 시각화하는 데 유용.datasets <- c("sf1", "sf2", "sf3", "sf4", "pl",
"as", "gu", "mp", "vi", "acs1", "acs3",
"acs5", "acs1/profile", "acs3/profile",
"acs5/profile", "acs1/subject",
"acs3/subject", "acs5/subject",
"acs1/cprofile", "acs5/cprofile")
acs1, acs3, acs5: 1년, 3년, 5년 단위로 수집된 미국 인구조사 데이터.sf1, sf2: 10년 단위의 요약 파일(Summary File).profile, subject, cprofile: 프로파일 데이터나 주제별 데이터를 포함.acs1 데이터셋의 변수 로드acs1_variables <- load_variables(year = 2019, dataset = "acs1", cache = TRUE)
acs1_variables
load_variables():year = 2019)와 데이터셋(dataset = "acs1")의 변수 목록을 가져옵니다.cache = TRUE: 변수 목록을 캐시에 저장하여 이후 작업에서 빠르게 접근 가능.acs1_variables는 변수 이름과 설명이 포함된 데이터프레임.race_variables <- acs1_variables |>
filter(str_detect(name, "B01001._001")) |>
mutate(concept_short = str_extract(concept, regex("(?<=\\().{11}")))
race_variables
filter():name) 중 "B01001._001" 패턴을 포함한 변수만 선택."B01001": 연령 및 성별과 관련된 인구 통계를 나타내는 변수.mutate():concept_short 추가.str_extract():concept 열에서 괄호 안에 있는 11자리 문자열을 추출.Age (Male) → Male.race_variables_names <- c("B01001A_001", "B01001B_001", "B01001C_001",
"B01001D_001", "B01001E_001", "B01001I_001")
race_variables_names: 인종별 총 인구를 나타내는 변수 이름 목록.fl_races_county <- get_acs(
year = 2019,
geography = "county",
state = "FL",
variable = race_variables_names)
get_acs():year = 2019: 2019년 데이터를 가져옵니다.geography = "county": 데이터 단위를 카운티로 설정.state = "FL": 플로리다주(FL) 데이터를 가져옵니다.variable = race_variables_names: 앞서 정의한 인종 관련 변수만 포함.이어서..
플로리다주 카운티별 인종 데이터를 지리정보(geometry)와 결합하여 시각화하는 과정을 보여줍니다.
get_acs() 호출:fl_races_county_geo <- get_acs(
year = 2019,
geography = "county",
state = "FL",
variable = race_variables_names,
geometry = TRUE)
fl_races_county_geo
get_acs() 주요 파라미터:year = 2019: 2019년 데이터를 가져옵니다.geography = "county": 데이터를 카운티 단위로 수집.state = "FL": 플로리다주 데이터를 대상으로 설정.variable = race_variables_names: 인종 통계를 나타내는 변수만 선택.geometry = TRUE: 각 카운티의 경계 정보(지리 정보)를 포함.fl_races_county_geo는 각 카운티의 인종 통계 데이터와 지리 정보를 포함한 데이터프레임(SF 객체)입니다.get_acs() 호출:fl_races_county_geo <- get_acs(
state = "FL",
geography = "county",
variables = race_variables_names,
summary_var = "B01001_001",
geometry = TRUE)
summary_var:summary_var = "B01001_001": 각 카운티의 전체 인구 데이터를 요약 변수로 추가.fl_races_county_geo는 각 인종의 수치(estimate), 전체 인구(summary_est), 그리고 지리 정보(geometry)를 포함한 데이터.with_race_percent <- fl_races_county_geo |>
mutate(percent = 100 * estimate / summary_est)
mutate(percent = 100 * estimate / summary_est):estimate: 특정 인종의 인구 수.summary_est: 카운티 전체 인구 수.percent: 인구 비율(%)로 계산된 값.with_race_percent는 각 인종의 퍼센트 값을 포함한 데이터프레임.with_race_percent <- with_race_percent |>
inner_join(race_variables, by = c("variable" = "name"))
inner_join():with_race_percent와 race_variables를 variable(from with_race_percent)과 name(from race_variables) 열을 기준으로 결합.race_variables:concept_short) 포함.variable)과 설명(concept_short)이 추가.with_race_percent |>
ggplot(aes(fill = percent)) +
facet_wrap(~concept_short) +
geom_sf(color = NA) +
theme_void() +
scale_fill_viridis_c() +
labs(fill = "% of population\n(2019 Census)")
aes(fill = percent):percent)로 지정.facet_wrap(~concept_short):concept_short)에 대해 별도의 지도를 생성.geom_sf(color = NA):color = NA: 경계선을 없앰.theme_void():scale_fill_viridis_c():viridis 색상 팔레트를 사용하여 퍼센트를 색상 그라데이션으로 표현.labs():최종결과
지도 시각화:
플로리다주의 각 카운티에 대해 특정 인종이 전체 인구에서 차지하는 비율(%)을 시각적으로 표시. 인구조사 데이터를 활용한 지리적 데이터 분석과 시각화의 훌륭한 예제입니다.
facet_wrap()을 통해 각 인종별로 독립된 지도 생성.
색상 그라데이션으로 인구 비율을 직관적으로 표현.
| 단계 | 설명 |
|---|---|
| 1. API 키 설정 | 인구조사 데이터를 사용하기 위해 API 키를 설정. API 키는 시스템에 저장되어 이후에도 재사용 가능. |
| 2. 데이터셋 탐색 | 원하는 연도의 데이터셋 변수 목록을 가져와 데이터 구조를 이해하고 분석에 필요한 변수 선택. |
| 3. 변수 필터링 | 인종 통계와 관련된 특정 변수만 필터링하여 효율적으로 데이터를 다룰 수 있도록 준비. |
| 4. 데이터 가져오기 | 플로리다주 카운티별 인종 데이터를 가져오며, 각 카운티의 경계 정보를 포함한 지리 정보도 함께 수집. |
| 5. 퍼센트 계산 | 특정 인종이 각 카운티의 전체 인구에서 차지하는 비율(%)을 계산하여 추가적인 분석이 가능하도록 준비. |
| 6. 데이터 결합 | 필터링된 변수와 변수 설명 데이터를 결합하여 분석 결과를 보다 직관적으로 이해할 수 있도록 구성. |
| 7. 시각화 | 카운티별 인종 비율을 색상으로 나타내는 지도를 생성하며, 각 인종별로 분리된 지도도 시각화. |
ggplot2와 geom_sf()를 활용한 지리적 시각화.이 표는 미국 인구조사 데이터를 수집하고 시각화하는 과정을 체계적으로 요약한 것입니다.