데이터 시각화

R을 이용한 통계청 API로 남은 기대 수명 알아보기

r-code-for-data-analysis 2023. 11. 11. 17:29

통계청 데이터를 쉽게 받는 패키지를 이용하여 편하게 데이터 분석을 할 수 있게 되었다 .
(패키지 만드신 분께 감사합니다. )
 
https://github.com/seokhoonj/kosis

GitHub - seokhoonj/kosis: 국가통계포털 Korean Statistical Information Service (Open API Service)

국가통계포털 Korean Statistical Information Service (Open API Service) - GitHub - seokhoonj/kosis: 국가통계포털 Korean Statistical Information Service (Open API Service)

github.com

 
 
통계청 사이트 회원 가입 수 API KEY 받기
https://kosis.kr/openapi/index/index.jsp

KOSIS 공유서비스

KOSIS 통계정보를 웹 또는 모바일앱 개발에 활용할 수 있도록 인터페이스(API)를 제공하는 서비스 입니다.

kosis.kr

 
 
#1. 패키지 설치 / 불러오기 / API KEY 삽입

#   # install from CRAN
# install.packages("kosis")
# 
# # install dev version
# devtools::install_github("seokhoonj/kosis")  
# 

library(kosis)

# set your api key
kosis.setKey(apiKey = "*****************")

# or permantly
usethis::edit_r_environ() # add KOSIS_API_KEY="your_api_key" in .Renviron

 
#2 어떤 데이터가 있는지 훓어보기

 
https://kosis.kr/statisticsList/statisticsListIndex.do?vwcd=MT_ZTITLE&menuId=M_01_01
주제별 데이터를 보려면 위 사이트에 가서 먼저 살펴봄
 

 
#3. 2021년 기준, 현재 나이에서 남은 수명이 얼마나 되는지 보자 (기대 여명) 
https://kosis.kr/statHtml/statHtml.do?orgId=101&tblId=DT_1B42&vw_cd=MT_ZTITLE&list_id=F_29&scrId=&seqNo=&lang_mode=ko&obj_var_id=&itm_id=&conn_path=MT_ZTITLE&path=%252FstatisticsList%252FstatisticsListIndex.do
위 사이트에서 다운로드 받아도 되지만 우리는 패키지를 이용해서 분석하지

 
 
#4. 데이터 받아오기

getStatList(vwCd = "MT_ZTITLE", parentListId = "F_29") # find table id of `life table`

# get stat data (Actuarial Life Table)
data <- getStatData(orgId = "101", tblId = "DT_1B42", objL1 = "ALL")
life_table <- castItem(statData = data, itemVar = "ITM_NM")

 
#5. 시각화 하기

life_table %>% 
  filter(PRD_DE ==  "2021") %>%  
  select(5,9,10) %>% 
  slice(seq(1, 101, by=10)) %>% 
  rename(나이 = colnames(.)[1],
         남은수명_남 = colnames(.)[2],
         남은수명_여 = colnames(.)[3]) %>% 
  mutate(나이 = fct_reorder(나이, -남은수명_남)) %>% 
  pivot_longer(-1, names_to = "성별", values_to = "남은수명") %>% 
  ggplot(aes(x=나이 , y=남은수명, fill=성별))+geom_col(position = "dodge")+
  scale_y_continuous(limits = c(0, 100))+
  geom_label(aes(label=round(남은수명)), 
             vjust = -0.2,
             position = position_dodge(width = .9))+
  theme_minimal()

 
내 나이가 50에 가까이 오니 남은 수명이 32세 정도이네...

이 세상에서 살아갈 날들을 소중히 여기며 살아야겠다.

728x90
반응형