install.packages(c("httr2", "jsonlite", "dplyr", "purrr", "tibble"))
library(httr2)
library(jsonlite)
library(dplyr)
library(purrr)
library(tibble)
# -------------------------------
# 1. Ustawienia
# -------------------------------
Sys.setenv(KACHELMANN_API_KEY = "KLUCZ_API")
lat <- 52.4064
lon <- 16.9252
# -------------------------------
# 2. Pobranie danych
# -------------------------------
url <- paste0(
"https://api.kachelmannwetter.com/v02/forecast/",
lat, "/", lon, "/3day?units=metric"
)
resp <- request(url) |>
req_headers(
Accept = "application/json",
`X-API-Key` = Sys.getenv("KACHELMANN_API_KEY")
) |>
req_error(is_error = function(resp) FALSE) |>
req_perform()
if (resp_status(resp) != 200) {
cat(resp_body_string(resp), "\n")
stop("API zwróciło błąd.")
}
raw <- resp_body_json(resp, simplifyVector = FALSE)
# -------------------------------
# 3. Tabela dzienna
# -------------------------------
daily <- map_dfr(raw$data, function(day) {
tibble(
date = day$dateTime,
day_name = day$dayName,
temp_max = day$tempMax,
temp_min = day$tempMin,
precip_current = day$precCurrent,
precip_prob = day$precProb,
precip_prob_1mm = day$precProb1mm,
precip_prob_10mm = day$precProb10mm,
wind_gust = day$windGust,
wind_speed = day$windSpeed,
wind_direction = day$windDirection,
sun_hours = day$sunHours,
cloud_coverage = day$cloudCoverage,
weather_symbol = day$weatherSymbol
)
})
print(daily)
View(daily)
# -------------------------------
# 4. Tabela pór dnia
# -------------------------------
get_value <- function(x, name, default = NA) {
if (!is.null(x[[name]])) x[[name]] else default
}
parts <- c("night", "morning", "afternoon", "evening")
tod <- map_dfr(raw$data, function(day) {
map_dfr(parts, function(part) {
x <- day$timeOfDay[[part]]
tibble(
date = day$dateTime,
part = part,
temp = get_value(x, "temp"),
temp_max = get_value(x, "tempMax"),
temp_min = get_value(x, "tempMin"),
precip_current = get_value(x, "precCurrent"),
precip_prob = get_value(x, "precProb"),
precip_prob_1mm = get_value(x, "precProb1mm"),
precip_prob_10mm = get_value(x, "precProb10mm"),
wind_gust = get_value(x, "windGust"),
wind_speed = get_value(x, "windSpeed"),
wind_direction = get_value(x, "windDirection"),
cloud_coverage = get_value(x, "cloudCoverage"),
weather_symbol = get_value(x, "weatherSymbol")
)
})
})
print(tod)
View(tod)
# -------------------------------
# 5. Surowa struktura też do podejrzenia
# -------------------------------
str(raw, max.level = 4)