Last active
March 29, 2019 21:34
-
-
Save bdemeshev/93c530dff02cb73b2530e78632a19b68 to your computer and use it in GitHub Desktop.
[Ежемесячное количество браков] #R #code #metrics #time_series
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(rio) # загрузка данных | |
library(tidyverse) # манипуляции | |
library(forecast) # прогнозировани | |
library(tsibble) # ряды богатой структуры | |
library(stringr) # строками | |
library(skimr) # описательные статистики | |
library(lubridate) # работа с датами | |
# данные скачиваются с fedstat.ru | |
# tools - install packages: rio, tidyverse, forecast | |
d = import("c:/Users/teacher.MAIN.000/Downloads/data.xls") | |
2006:2018 | |
paste0("y", 2006:2018) | |
colnames(d) = c("region", "unit", "period", paste0("y", 2006:2018)) | |
glimpse(d) | |
d2 = tail(d, -2) | |
glimpse(d2) | |
d3 = mutate_at(d2, vars(y2006:y2018), as.numeric) | |
glimpse(d3) | |
skim(d3) | |
d4 = select(d3, -unit) %>% filter(nchar(period) < 14) | |
# d4 = select(d3, -unit) %>% filter(!str_detect(period, "-")) | |
glimpse(d4) | |
skim(d4) | |
report = group_by(d4, region) %>% summarise(n_obs = n()) | |
table(report$n_obs) | |
qplot(data = report, x = n_obs) | |
d5 = group_by(d4, region) %>% filter(n() == 12) %>% ungroup() | |
glimpse(d5) | |
d6 = mutate(d5, month = rep(1:12, nrow(d5)/12)) | |
glimpse(d6) | |
table(d6$period, d6$month) | |
d7 = select(d6, -period) | |
glimpse(d7) | |
d8 = gather(d7, key = "year", value = "marriage", -month, -region) | |
glimpse(d8) | |
d9 = mutate(d8, date = ymd( | |
paste0(str_remove(year, "y"), "-", month, "-01"))) | |
glimpse(d9) | |
d10 = select(d9, -year, -month) | |
glimpse(d10) | |
export(d10, "c:/Users/teacher.MAIN.000/Downloads/marriage.csv") | |
d11 = mutate(d10, date = yearmonth(date)) | |
glimpse(d11) | |
mar_tsibble = as_tsibble(d11, index = date, key = id(region)) | |
mar_russia = filter(mar_tsibble, region == "643 Россия (код по ОКСМ)") | |
mar_ts = as.ts(mar_russia) | |
mar_ts | |
ggtsdisplay(mar_ts) | |
ggseasonplot(mar_ts) | |
model = auto.arima(mar_ts) | |
model | |
fcst = forecast(model, h = 12) | |
fcst | |
autoplot(fcst) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment