# Підключаємо бібліотеку для онлайн запитів
library(request)

# Створюємо запит на Prozorro
data <- api("http://api.openprocurement.org/api/2.3/tenders") %>%
  api_query(descending="1", opt_pretty="1") %>%
  http()

# Попередня сторінка
prev = data$next_page$offset

# Замінити prev на актуальний офсет
data2 <- api("http://api.openprocurement.org/api/2.3/tenders") %>%
  api_query(descending="1", opt_pretty="1", offset = "2017-04-10T12:59:22.515411+03:00") %>%
  http()

# Переглянемо стуктуру даних
data$data[1]

# Збережемо id 100 останніх тендерів
tenders <- unlist(lapply(data$data, '[[', "id"))

# Створимо пустий перелік для даних з тендерів 
tenders_content = list()

# Завантажимо інформацію з усіх тендерів
for (i in 1:length(tenders)) {
  d <- api(paste0("http://api.openprocurement.org/api/2.3/tenders/",tenders[i])) %>%
    http()
  tenders_content[[i]] <- d
}

#Переглянемо зміст тендеру
tenders_content[[1]]

# Визначимо методи закупівлі та очікувану вартість

method <- unlist(lapply(tenders_content, function (x) x$data$procurementMethod))
amounts <- unlist(lapply(tenders_content, function (x) x$data$value$amount))

# Дослідимо їх
table(method)
hist(amounts)
boxplot(amounts~method)

# Переглянемо завершені закупівлі
awarder_tenders <- tenders_content[!unlist(lapply(tenders_content, function (x) is.null(x$data$awards[[1]]$value$amount)))]
awards <- unlist(lapply(awarder_tenders, function (x) x$data$awards[[1]]$value$amount))
amounts <- unlist(lapply(awarder_tenders, function (x) x$data$value$amount))

plot(awards,amounts)

# Розрахуємо економію
sum(amounts-awards)

# Робота з XML

library(XML)

data <- api("https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange") %>%
  api_query(data="20170410") %>%
  http()

xmlfile <- xmlParse(data)
title <- xpathSApply(xmlfile, "//currency/txt", xmlValue)
rate <- as.numeric(xpathSApply(xmlfile, "//currency/rate", xmlValue))

