knitr::opts_chunk$set(collapse = T, comment = "#>") #library(weatherapi) devtools::load_all()
This package wraps the Weather API, available from: weatherapi.com. The Weather API provides access to real-time and historical weather info, astronomy, time zone, and sports data.
This package relies on the API key provided by the Weather API. To get started on using this package, please follow these steps:
usethis::edit_r_environ()
API_KEY = <your_api_key>
This table provides descriptions of the possible error codes.
|Error Code|Description| |---|---| |400|Invalid/missing location argument or internal server error| |401|Invalid/missing API key| |403|API Key disabled or has reached maximum calls quota|
This function can be used to see the API key that you have set during the setup step above. To see if you have entered your API key correctly, you can run api_key()
and it will output the API key that you have set in the .Renviron file.
This function can also be used as another way to set the API key. Note that this will not change the value of the API key in the .Renviron file, but it will change the API key being used when calling the functions. To set a temporary API key, you can run api_key(force=TRUE)
which will require you to enter your API key in the interactive console. Enter your API key in the R console and press enter. You have now changed the API key that will be used by the functions (but not in the .Renviron file).
api_key(force=FALSE)
force
: A boolean to force-set new API key for current environment. This is done to force-set a new API key to TRUE, the default value is FALSE.
A vector containing the API key
api_key()
# To display API key that was set in the .Renviron file
api_key(force=TRUE)
# To change the API key
get_current_weather(location, aqi="yes")
location
: A vector of location
air_quality
: A string of "yes" or "no" to show air quality information. The default is show air quality information ("yes").
A data frame of current weather information
get_current_weather("Kelowna")
get_current_weather(c("Kelowna", "Vancouver"), "no")
This function is used to get the current real-time weather information of a specified location. Air quality information of that location is included by default and can be omitted by setting aqi="no"
. The resulting information will be a data frame.
For instance, if you want to get the current real-time weather condition for Kelowna, you can use:
get_current_weather("Kelowna")
If you want to get a list of current real-time weather condition for Kelowna, Vancouver, and Toronto, you can use:
cities <- c("Kelowna", "Vancouver", "Toronto") get_current_weather(cities)
The table below summarizes the data type and the descriptions of the returned variables in the dataframe.
| Variable | Type | Description | |----------|------|-------------| |location.name|chr|Name of the requested location| |location.region|chr|Name of the location region| |location.country|chr|Name of the location country| |location.lat|num|Latitude in decimal degree| |location.lon|num|Longitude in decimal degree| |location.tz_id|chr|Time zone| |location.localtime_epoch|int|Local time in epoch| |location.localtime|chr|Local time in yyyy-MM-dd HH:mm format| |current.last_updated_epoch|int|Local time when the real time data was updated| |current.last_updated|chr|Local time when the real time data was updated in unix time| |current.temp_c|num|Temperature in celsius| |current.temp_f|num|Temperature in fahrenheit| |current.is_day|int|Show day condition icon or night icon (1 = Yes 0 = No)| |current.condition.text|chr|Weather condition text| |current.condition.icon|chr|Weather icon url| |current.condition.code|int|Weather condition unique code| |current.wind_mph|num|Wind speed in miles per hour| |current.wind_kph|num|Wind speed in kilometer per hour| |current.wind_degree|int|Wind direction in degrees| |current.wind_dir|chr|Wind direction as 16 point compass. e.g.: NSW| |current.pressure_mb|num|Pressure in millibars| |current.pressure_in|num|Pressure in inches| |current.precip_mm|num|Precipitation amount in millimeters| |current.precip_in|num|Precipitation amount in inches| |current.humidity|int|Humidity as percentage| |current.cloud|int|Cloud cover as percentage| |current.feelslike_c|num|Feels like temperature as celcius| |current.feelslike_f|num|Feels like temperature as fahrenheit| |current.vis_km|num|Visibility in kilometer| |current.vis_miles|num|Visibility in miles| |current.uv|num|UV Index| |current.gust_mph|num|Wind gust in miles per hour| |current.gust_kph|num|Wind gust in kilometer per hour| |current.air_quality.co|num|Carbon Monoxide (μg/m3)| |current.air_quality.no2|num|Nitrogen dioxide (μg/m3)| |current.air_quality.o3|num|Ozone (μg/m3)| |current.air_quality.so2|num|Sulphur dioxide (μg/m3)| |current.air_quality.pm2_5|num|PM2.5 (μg/m3)| |current.air_quality.pm10|num|PM10 (μg/m3)| |current.air_quality.us.epa.index|int|US - EPA standard(1-Good, 2-Moderate, 3-Unhealthy for Sensitive group, 4-Unhealthy, 5-Very unhealthy, 6-Hazardous)| |current.air_quality.gb.defra.index|int|UK Defra Index (1-Low, 10-High)|
get_time_zone(location)
location
: A vector of location
A data frame of local time-zone information
get_time_zone("Kelowna")
get_time_zone(c("Kelowna", "Vancouver"))
This function is used to get the time zone and local time information of a specified location. The resulting information will be a data frame.
For instance, if you want to get the time zone and local time information of Kelowna, you can use:
get_time_zone("Kelowna")
If you want to get the time zone and local time information of multiple locations, you can use:
cities <- c("Kelowna","Vancouver","Toronto") get_time_zone(cities)
The table below summarize the data type and the descriptions of the returned variables in the dataframe.
| Variable | Type | Description | |----------|------|-------------| |location.name|chr|Name of the requested location| |location.region|chr|Name of the location region| |location.country|chr|Name of the location country| |location.lat|num|Latitude in decimal degree| |location.lon|num|Longitude in decimal degree| |location.tz_id|chr|Time zone id| |location.localtime_epoch|int|Local time in epoch| |location.localtime|chr|Local time in yyyy-MM-dd HH:mm format|
get_sports_events(location, sport)
location
: A vector of location
sport
: A string of sport type ("football","cricket","golf")
A data frame of upcoming sports events in a location
get_sports_events("London", "football")
get_sports_events(c("London", "Oxford"))
This function is used to get a list of all upcoming sports events (football, cricket, golf) in a specified location. The resulting information will be a data frame.
For instance, if you want to get a list of all upcoming sports events (football, cricket, golf) in London, you can use:
get_sports_events("London", "football")
The table below summarizes the data type and the descriptions of the returned variables in the dataframe.
| Variable | Type | Description | |----------|------|-------------| |football.stadium|chr|Name of stadium| |football.country|chr|Country| |football.region|chr|Region| |football.tournament|chr|Tournament name| |football.start|chr|Start local date and time for event in yyyy-MM-dd HH:mm format| |football.match|chr|Match name|
This is a helper function to send a request to retrieve data from weatherapi.com.
data_request(query)
query
: A list that contains information of city, date, and api_key, represented by q
, dt
, and key
, respectively.
A HTTP response.
data_request(list(key="9d56997213e54667a41172101221602", q="Shanghai",dt="2022/01/01"))
This function is an API wrapper to retrieve astronomy data from weatherapi.com. Given a desired city and date, the wrapper will return astronomy data such as sunset time and moon rise time. Error messages are given when a user enters invalid input. A helper function is used for sending request.
get_astronomy(city, date)
city
: A string indicating city (e.g., "London", "Beijing").
date
: A string of the form yyyy-mm-dd indicating date (e.g., "2022-02-10").
A dataframe with the columns sunrise
, sunset
, moonrise
, moonset
, moon_phase
, and moon_illumination
.
get_astronomy("Beijing", "2022-01-10")
get_astronomy("Kelowna", "2021-06-06")
get_history_astro_information(key,q,dt)
key
: A string containing the API key
q
: A string containing the location, which can be an US Zipcode, UK Postcode, Canadian Postalcode, IP address, Latitude/Longitude (decimal degree) or city name.
dt
: A string containing the date of query, which should be within the last 7 days.
A data frame containing the astronomical information for the day.
get_history_astro_information("YourAPIKeyHere","London","2022-02-12")
get_history_astro_information("YourAPIKeyHere","Beijing","2022-02-14")
The table below summarizes the data type and the descriptions of the returned variables in the dataframe.
| Variable | Type | Description | |----------|------|-------------| |sunrise|chr|The sunrise time| |sunset|chr|The sunset time| |moonrise|chr|The moonrise time| |moonset|chr|The moonset time| |moon_phase|chr|The moon phase| |moon_illumination|chr|The illumination of the moon|
get_history_daily_weather(key,q,dt)
key
: A string containing the API key
q
: A string containing the location, which can be an US Zipcode, UK Postcode, Canadaian Postalcode, IP address,
Latitude/Longitude (decimal degree) or city name.
dt
: A string containing the date of query, which should be within the last 7 days.
A data frame containing the daily weather information of the day.
get_history_daily_weather("YourAPIKeyHere","London","2022-02-12")
get_history_daily_weather("YourAPIKeyHere","Beijing","2022-02-14")
The table below summarizes the data type and the descriptions of the returned variables in the dataframe.
| Variable | Type | Description | |----------|------|-------------| |maxtemp_c|num|Daily max temperature (Celsius)| |maxtemp_f|num|Daily max temperature (Fahrenheit)| |mintemp_c|num|Daily min temperature (Celsius)| |mintemp_f|num|Daily min temperature (Fahrenheit)| |avgtemp_c|num|Daily average temperature (Celsius)| |avgtemp_f|num|Daily average temperature (Fahrenheit)| |maxwind|num|Daily max wind speed (miles per hour)| |maxwind_kph|num|Daily max wind speed (kilometers per Hour)| |totalprecip_mm|num|Daily total Precipitation(mm)| |totalprecip_in|num|Daily total Precipitation(in)| |avgvis_km|num|Daily average visibility in kilometers| |avgvis_miles|num|Daily average visibility in miles| |avghumidity|num|Daily average humidity| |condition.text|chr|Weather condition text| |condition.icon|chr|Weather icon url| |condition.code|num|Weather condition unique code| |uv|num|UV Index|
get_history_hourly_weather(key,q,dt,h)
key
: A string containing the API key
q
: A string containing the location, which can be an US Zipcode, UK Postcode, Canadian Postalcode, IP address, Latitude/Longitude (decimal degree) or city name.
dt
: A string containing the date of query, which should be within the last 7 days.
h
: An integer containing the hour of query, which be in the range of 0 to 23.
A data frame containing the daily weather information of the hour in the day.
get_history_hourly_weather("YourAPIKeyHere","London","2022-02-12",4)
get_history_daily_weather("YourAPIKeyHere","Beijing","2022-02-14",23)
The table below summarizes the data type and the descriptions of the returned variables in the dataframe.
| Variable | Type | Description | |----------|------|-------------| |city |chr |The desired city| |region |chr |The region of the city| |country |chr |The country of the city| |lat |num |The latitude of the city| |lon |num |The lognitude of the city | |sunrise |chr |The sunrise time of the city on a given date| |sunset |chr |The sunset time of the city on a given date| |moonrise |chr |The moonrise time of the city on a given date|| |moonset |chr |The moonset time of the city on a given date|| |moon_phase|chr |The moon phase of the city on a given date|| |moon_illumination |chr |The illumination of the moon of the city on a given date|| |date |chr |The given date|
The following exercise shows how to get current temperature and feels-like temperature data using the get_current_weather() function and plots it as a line chart.
library(ggplot2) library(reshape2) # Get current weather data loc <- c("London", "New York", "Paris", "Melbourne", "Singapore") data <- get_current_weather(loc,"no") # Get temperature info and melt dataframe data <- data[c("location.name", "current.temp_c", "current.feelslike_c")] data <- melt(data) # Plot temperature ggplot(data=data, aes(x=location.name, y=value, group=variable, linetype=variable)) + geom_line()+ geom_point()+ labs(title="Temperature by Location", subtitle="(in celcius)", x="", y="", linetype="")
The following exercise shows how to extract the time-zone of different locations and plot it in a world map.
# Get local time zone data loc <- c("London", "Los Angeles", "Buenos Aires", "Melbourne", "Singapore") data <- get_time_zone(loc) # Get the world map coordinates library(tidyverse) world <- map_data("world") # Plot time zone of different location in world map ggplot() + geom_map( data = world, map = world, aes(long, lat, map_id = region), color = "lightgray", fill = "lightgray") + geom_text(data=data, aes(location.lon, location.lat, label=location.name)) + geom_text(data=data, aes(location.lon, location.lat, label=location.localtime),nudge_y = -10) + labs(title="Current Time-zone of Different Locations in the World", x="", y="")
The following exercise will show how to get min and max temperature in the past 7 days using the get_history_daily_weather() function and plot it as a line chart.
library(ggplot2) library(reshape2) min_temp<- vector() max_temp<- vector() td <- Sys.Date() dates <- c() for (i in 6:0){ dates <- c(dates, as.character(td-i)) } for(i in seq_along(dates)){ max_temp<-append(max_temp,get_history_daily_weather("London",dates[i])$maxtemp_c) min_temp<-append(min_temp,get_history_daily_weather("London",dates[i])$mintemp_c) } df <- data.frame(dates,max_temp, min_temp) mdf <- melt(df,id.vars="dates") ggplot(mdf, aes(x=dates, y=value, colour=variable, group=variable )) + geom_line()
The following exercise shows how to get hourly temperature in a day using the get_history_hourly_weather() function and plot it as a line chart.
library(ggplot2) library(reshape2) temp<- vector() hour<-0:23 for(i in seq_along(hour)){ temp<-append(temp,get_history_hourly_weather("London","2022-02-14",hour[i])$temp_c) } df <- data.frame(hour,temp) ggplot(df, aes(x=hour, y=temp)) + geom_line()
The code below describes how to get the moon_illumination at Beijing on same date from year 2011 to year 2021 using the get_astronomy
function and plot the result.
```r library(ggplot2)
years <- c() moon_illuminations <- c()
for (i in 2011:2021){ year <- as.character(i) date <- paste(year, "-06-06", sep="")
# get astronomy data on desired date at Beijing data <- get_astronomy("Beijing", date)
# extract moon_illumination moon_illumination <- data$moon_illumination
years <- c(years, year) moon_illuminations <- c(moon_illuminations, moon_illumination) }
result <- data.frame(year=years, moon_illumination=moon_illuminations)
ggplot(data=result, aes(x=year, y=moon_illumination, group=1)) + geom_line()+ labs(title="Moon illumination at Beijing on July 6th", x="", y="", linetype="")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.