Learn R Programming

aiRly

aiRly is an unofficial R wrapper for Airly, platform which mission is to monitor and inform millions of people about the current state of air quality.

Installation

You can install current development version of aiRly from GitHub with:

devtools::install_github("piotrekjanus/aiRly")

Set developer account

First, you should start with setting your Airly developer account at Airly developer. After you receive key, we can check air condition!

Example

This is a basic example of package usage.

Let’s find out if there are any near stations somewhere in Krakow, Poland. We will look for stations in a range of 20 km. We set max_results to -1 in order to get all stations in the neighborhood.

library(aiRly)

api_key <- Sys.getenv("api_key")
aiRly::set_apikey(api_key)

stations <- get_nearest_installations(50.11670, 19.91429, max_distance = 20, max_results = -1)

Let’s filter only for Airly stations and choose those which are located at the highest and lowest point a.s.l.

minmax_station <- stations %>%
                    filter(is_airly) %>% 
                    summarize(min_elevation_id = id[which.min(elevation)], 
                              max_elevation_id = id[which.max(elevation)])

h_station <- get_installation_measurements(minmax_station$max_elevation_id)
l_station <- get_installation_measurements(minmax_station$min_elevation_id)

Ok, we have just received information about current state, last 24h history and forecasts for next day for both installations.

Let’s make some visualizations

library(ggplot2)
library(gridExtra)

g1 <- ggplot() + 
        geom_col(h_station$history, mapping = aes(x=time$from, y = measure$PM25, fill="High"),  alpha = 0.5) +
        geom_col(l_station$history, mapping = aes(x=time$from, y = measure$PM25, fill="Low"), alpha = 0.6) +
        scale_fill_manual(values=c("#40798C", "#CFD7C7")) +
        theme_minimal() +
        xlab("time") +
        ylab("PM25") +
        ggtitle("History") +
        theme(panel.grid.major.x = element_blank(),
              panel.grid.minor.x = element_blank(),
              plot.title = element_text(hjust=0.5),
              legend.position="top") +
        labs(fill="Installation")
    
g2 <- ggplot() + 
        geom_col(h_station$forecast, mapping = aes(x=time$from, y = measure$PM25, fill="High"),  alpha = 0.5) +
        geom_col(l_station$forecast, mapping = aes(x=time$from, y = measure$PM25, fill="Low"), alpha = 0.6) +
        scale_fill_manual(values=c("#40798C", "#CFD7C7")) +
        theme_minimal() +
        xlab("time") +
        ylab("PM25") +
        ggtitle("Forecast") +
        theme(panel.grid.major.x = element_blank(),
              panel.grid.minor.x = element_blank(),
              plot.title = element_text(hjust=0.5),
              legend.position="top") +
        labs(fill="Installation") 

grid.arrange(g1, g2, ncol = 2, nrow = 1)

We can see that most of the time, air quality is worse (and will be) in lower part of Krakow. Ok, but are those sensors readings indicating high pollution? We can check it using get_indexes function, which fill translate values of AIRLY_CAQI variable

indexes <- get_indexes()
airly_caqi <- indexes %>% filter(name == "AIRLY_CAQI")
airly_caqi[is.na(airly_caqi)] <- Inf 

history_high <- h_station$history
history_high$status <- unlist(lapply(history_high$index$AIRLY_CAQI, 
                        function(x) airly_caqi[x >= airly_caqi$minValue & 
                                               x <= airly_caqi$maxValue, "description"]))

history_low <- l_station$history
history_low$status <- unlist(lapply(history_low$index$AIRLY_CAQI, 
                        function(x) airly_caqi[x >= airly_caqi$minValue &
                                               x <= airly_caqi$maxValue, "description"]))

ggplot() +
  geom_rect(history_high, mapping = aes(xmin=time$from, xmax = time$to, 
                                        ymin=0, ymax=.1, fill = status)) +
  geom_rect(history_low, mapping = aes(xmin=time$from, xmax = time$to, 
                                       ymin=0.2, ymax=.3, fill = status))+
  scale_fill_manual(values = c("Very Low" = "#6BC926",
                               "Low"    = "#D1CF1E",
                               "Medium" = "#EFBB0F",
                               "High"   = "#EF7120",
                               "Very High" ="#EF2A36",
                               "Extreme" = "#B00057",
                               "Airmageddon!" = "#770078")) +
  annotate("text", x = min(history_high$time$from), y = 0.25, label = "High a.s.l") +
  annotate("text", x = min(history_low$time$from), y = 0.05, label = "Low a.s.l") +
  theme_minimal() +
  theme(panel.grid = element_blank(),
        axis.text.y = element_blank()) +
  ylab("") +xlab("")

After we made few requests, we would like to check how many we have left. For that purpose, simply use remaining_requests

rem_req <- remaining_requests()
cat("Available requests \n", rem_req$remaining, "/", rem_req$limit)
#> Available requests 
#>  79 / 100

Copy Link

Version

Install

install.packages('aiRly')

Monthly Downloads

205

Version

0.1.0

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Piotr Janus

Last Published

March 19th, 2020

Functions in aiRly (0.1.0)

create_airly_location

Creates an object representing Airly location
get_installation_measurements

Get Airly measurements for any geographical location given installation id
remaining_requests

Get information about remaining API requests
replace_null

Replaces NULL with NA for nested lists. Useful when NULL value leads to error while object casting
get_measurements_info

Get measures used in Airly
.get_apikey

Get Airly apikey
.base_url

Return base url of Airly API v2
create_airly_measurement

Creates an object representing Airly measurement
set_apikey

Set Airly apikey
get_nearest_installations

Get Airly nearest installations to given point
build_forecast_df

Creates object containing information about history data for given API response
get_nearest_measurements

Get Airly nearest measurements to given point
get_indexes

Get Airly available indexes
get_installation_by_id

Get Airly installation by id
validate_airly_location

Checks whether the given object is correctly defined airly_location class
validate_airly_measurement

Checks whether the given object is correctly defined airly_measurement class
parse_json

Parses a json response
print.airly_measurement

Print for "airly_measurement" type objects
validate_airly_api_response

Checks if the given response is not empty and that it did not return an error http code.
create_airly_meta

Creates a data.frame representing Airly meta
create_request_url

Creates a request url based on the given base url and passed paths. The json extensions is added automatically.
is_airly_location

Checks whether the given object is of the class airly_location
.send_request

Sends a request to the specified url and retrieves it's content.
get_content

Retrieves the response content
validate_airly_meta

Checks whether the given object is correctly correctly defined
is_airly_measurement

Checks whether the given object is of the class airly_measurement
get_point_measurements

Get Airly measurements for any geographical location
is_airly_api_response

Checks whether the given object is of the class airly_api_response
add_path

Adds the given path to the given url
create_airly_api_response

Creates an object representing a response from the Airly API. Also every API call return information about current limits What is used to assign variables in pkg.env
assert_ids

Checks whether ids are correctly defined. If not throws an error
build_current_df

Creates an object representing Airly measurement
assert_coordinates

Checks whether apikey is correctly set
build_history_df

Creates object containing information about history data for given API response
assert

Asserts a given expression and throws an error if it returns FALSE
add_json_extension

Adds the json extension to the given url
assert_apikey

Checks whether apikey is correctly set