Skip to content

Instantly share code, notes, and snippets.

@IshidaMotohiro
Created January 22, 2016 03:19
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 IshidaMotohiro/0e7a1b7552f859704a00 to your computer and use it in GitHub Desktop.
Save IshidaMotohiro/0e7a1b7552f859704a00 to your computer and use it in GitHub Desktop.
政府統計の総合窓口を利用す
---
title: "政府統計の総合窓口を利用する"
author: "Ishida Motohiro"
date: "2016年1月20日"
output: html_document
---
総務省統計局の総合窓口 (e-Stat) の API 機能を利用する
# 利用登録
API 機能を利用するにはユーザー登録が必要です。
[利用登録](http://www.e-stat.go.jp/api/regist-login/) から登録し、アクセス用の ID (文字列) を取得します。
取得したIDを R に登録します。
```{r echo = FALSE, warning=FALSE, message=FALSE,error=FALSE}
ids <- "取得したAPIトークン"
```
# Rの追加パッケージ
ネットワーク越しにデータを取得する作業を簡単にするため、追加のパッケージをインストールします。
```{r echo = FALSE,message=FALSE}
if (! require (RCurl, quietly = FALSE) ) {install.packages ("RCurl") ; require(RCurl, quietly = FALSE)}
if (! require (XML, quietly = FALSE) ) {install.packages ("XML") ; require(XML, quietly = FALSE)}
if (! require (ggplot2, quietly = FALSE) ) {install.packages ("ggplot2") ; require(ggplot2, quietly = FALSE)}
if (! require (dplyr, quietly = FALSE) ) {install.packages ("dplyr") ; require(dplyr, quietly = FALSE)}
```
# データの取得
e-Stat の[ガイド](http://www.soumu.go.jp/main_content/000320558.pdf) に、餃子の街として知られる宇都宮市と浜松市で各家庭の月別餃子支出額を抽出する例があるので、これを試してみます。
データを指定するための URI を生成してAPI にアクセスし、データをXML形式で取得します。
次にXML を解析した上で、Rで利用できるデータ形式(データフレーム)に変換します。
```{r echo = FALSE}
urlx <- paste ("http://api.e-stat.go.jp/rest/1.0/app/getStatsData?appId=", ids,
"&statsDataId=0003013276&cdArea=09003,22004&cdCat01=010920070&cdTimeFrom=2012000101&cdTimeTo=2015001031",
sep = "")
gyoza <- xmlParse(urlx)
gyoza <- getNodeSet(gyoza, "//GET_STATS_DATA//STATISTICAL_DATA//DATA_INF//VALUE" )
df <- do.call ("rbind", lapply (gyoza, xmlAttrs))
df <- as.data.frame(df)
value <- as.numeric (unlist(lapply(gyoza,xmlValue)))
df$value <- value
df$time <- as.Date(as.character(df$time), "%Y00%m%d")
```
## データの要約
取得したデータの要約統計量を表示します。
```{r}
summary(df)
```
## 時系列グラフの作成
2つの都市ごとに経時変化を確認できるグラフを作成します。
```{r}
df %>% ggplot(aes(x = time, y = value)) + geom_line(aes(color = area)) + labs (y = "支出額", x = "年月", color = "地域" ) + scale_color_hue( name = "地域", labels=c("宇都宮", "浜松")) + labs(title = "宇都宮市と浜松市の餃子支出")
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment