#' City forecast
#'
#' forecast_data function will get FIVE days temperature forecast data from OpenWeatherMap API(\url{https://openweathermap.org}).
#'
#' @param city character, a city name
#' @param time character, default is 'day_average'
#'
#' day_average: Get average temperature in each day
#'
#' hours: Get temperature of every 3 hours
#'
#' @return a data.frame, five days temperature forecast of the city
#'
#' @examples
#' forecast_data("stockholm")
#'
#' @export
forecast_data <- function(city, time = "day_average") {
d <- .get_weather_data(city)
# temperature data
df <- d$list
# tranfer temperature from Kelvins to Celsius
temp <- df$main$temp - 273.15
# country
country <- rep(d$city$country, nrow(df))
if (time == "day_average") {
# date
date <- substr(df$dt_txt, 1, 10)
df <- data.frame(date = date, temp = temp, country = country)
# get average for everyday
df <- df %>%
dplyr::select(date, temp, country) %>%
dplyr::group_by(date, country) %>%
dplyr::summarize(mean_temp = mean(temp))
df <- data.frame(df)
}
if (time == "hours") {
# country <- rep(d$city$country, nrow(df))
date <- substr(df$dt_txt, 1, 16)
df <- data.frame(date = date, temp = temp, country = country)
}
return (df)
}
.get_weather_data <- function(city) {
# key for the api
key <- "3c656bd3014279a8f41b90522c014977"
url <- paste0("https://api.openweathermap.org/data/2.5/forecast?q=", city, "&appid=", key)
if (httr::status_code(httr::GET(url)) == 404) {
stop("city not found!")
}
d <- jsonlite::fromJSON(url)
return (d)
}
#' @importFrom magrittr %>%
#' @importFrom jsonlite fromJSON
#' @importFrom httr GET
#' @importFrom httr status_code
#' @import dplyr
NULL
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.