Package 'vayuayan'

Title: Air Quality Data from CPCB, OAQ, and WUSTL Satellite PM2.5
Description: Download and analyze air pollution data from three sources. CPCB (Central Pollution Control Board) CAAQMS stations provide historical and real-time PM2.5, PM10, and AQI readings across 400+ sites in India. OAQ (Open Air Quality) aggregates low-cost sensor networks such as Airnet, also in India. WUSTL ACAG V5GL04 provides satellite-derived PM2.5 at 1 km resolution globally (1998-2022). Includes geospatial station matching, AQI categorization, and NetCDF raster extraction for arbitrary regions.
Authors: Saket Choudhary [aut, cre], Mahesh Kumar Prajapat [aut], Darakhshan [email protected] Nehal [ctb]
Maintainer: Saket Choudhary <[email protected]>
License: MIT + file LICENSE
Version: 0.2.0.9001
Built: 2026-09-21 11:11:02 UTC
Source: https://github.com/saketlab/vayuayanR

Help Index


Analyze station data

Description

Comprehensive analysis of station data

Usage

analyze_station_data(data)

Arguments

data

List of cities with nested stations

Value

List with analysis results


Clean station name

Description

Convert station name to clean underscore-separated format

Usage

clean_station_name(station_name)

Arguments

station_name

Original station name string

Value

Cleaned station name with underscores


Add coordinates to station list

Description

Add lat/lon coordinates to a station data frame by querying the CPCB live coordinates API (iit_rss_feed_with_coordinates). This is the same source used by the Python vayuayan package and returns authoritative coordinates directly from CPCB – no geocoding, no rate limiting, no NAs for oddly-named stations.

Falls back to Nominatim geocoding for any stations not found in the CPCB response (e.g. offline stations absent from the live feed).

Usage

cpcb_add_coords(stations)

Arguments

stations

Data frame from cpcb_get_station_list()

Value

Same data frame with lat and lon columns added

Examples

## Not run: 
stations <- cpcb_get_station_list("Mumbai")
stations_with_coords <- cpcb_add_coords(stations)
head(stations_with_coords)

## End(Not run)

Download city-level AQI data

Description

Download daily PM2.5 AQI data for a city from the CPCB data repository for a given year. Data is saved as a CSV file with one row per day and one column per month.

Usage

cpcb_download_city_data(city, year, save_location)

Arguments

city

Character. City name (e.g. "Delhi", "Mumbai").

year

Integer. Year for data (e.g. 2022).

save_location

Character. Full file path to save the downloaded CSV.

Value

Data frame preview (first 6 rows) of the downloaded data, invisibly. The full data is saved to save_location.

Examples

## Not run: 
cpcb_download_city_data(
  city          = "Delhi",
  year          = 2022,
  save_location = tempfile(fileext = ".csv")
)

## End(Not run)

Download station-level AQI data

Description

Download daily PM2.5 AQI data for a single CPCB monitoring station for a given year. Data is saved as a CSV file with one row per day and one column per month.

Usage

cpcb_download_station_data(station_id, year, save_location)

Arguments

station_id

Character. Station ID from cpcb_get_station_list() (e.g. "site_103").

year

Integer. Year for data (e.g. 2022).

save_location

Character. Full file path to save the downloaded CSV.

Value

Data frame preview (first 6 rows) of the downloaded data, invisibly. The full data is saved to save_location.

Examples

## Not run: 
cpcb_download_station_data(
  station_id    = "site_103",
  year          = 2022,
  save_location = tempfile(fileext = ".csv")
)

## End(Not run)

Get all India monitoring stations

Description

Get all air quality monitoring stations in India from CPCB live dashboard.

Usage

cpcb_get_all_india()

Value

List of station data

Examples

## Not run: 
stations <- cpcb_get_all_india()
df <- stations_to_dataframe(stations)
head(df)

## End(Not run)

Get list of cities in a state

Description

Get list of cities in a given state from CPCB.

Usage

cpcb_get_city_list(state)

Arguments

state

Character. State name (e.g. "Maharashtra", "Delhi").

Value

Character vector of city names

Examples

## Not run: 
cities <- cpcb_get_city_list("Maharashtra")
head(cities)

## End(Not run)

Fetch complete station and city list from CPCB

Description

Fetch the complete list of all India stations and cities from CPCB.

Usage

cpcb_get_complete_list()

Value

List containing station and city data

Examples

## Not run: 
all_data <- cpcb_get_complete_list()
names(all_data)

## End(Not run)

Get file path for CPCB data download

Description

Get file path for downloading data from CPCB. Used internally by cpcb_download_city_data() and cpcb_download_station_data().

Usage

cpcb_get_file_path(
  station_id = "",
  station_name = "",
  state = "",
  city = "",
  year = "",
  frequency = "daily",
  data_type = "cityLevel"
)

Arguments

station_id

Character. Station ID (e.g. "site_103").

station_name

Character. Station name.

state

Character. State name.

city

Character. City name.

year

Integer or character. Year for data (e.g. 2022).

frequency

Character. Data frequency: "daily" or "hourly".

data_type

Character. Type of data: "cityLevel" or "stationLevel".

Value

List of file path information with filePath and year elements

Examples

## Not run: 
paths <- cpcb_get_file_path(
  city = "Delhi", frequency = "daily",
  data_type = "cityLevel"
)
str(paths[[1]])

## End(Not run)

Get live AQI data

Description

Get live AQI data with flexible parameters. Automatically resolves station from coordinates or IP location if not provided.

Usage

cpcb_get_live_aqi_data(
  station_id = NULL,
  coords = NULL,
  date = NULL,
  hour = NULL
)

Arguments

station_id

Optional character. Station ID. If NULL, nearest station is found automatically using coords or IP geolocation.

coords

Optional numeric vector c(lat, lon). Used to find nearest station if station_id is not provided.

date

Optional character. Date in "YYYY-MM-DD" format. Defaults to today.

hour

Optional integer (0–23). Hour of the day. Defaults to the most recent full hour.

Value

List with processed live AQI data

Examples

## Not run: 
# Get live AQI at current location and time
aqi <- cpcb_get_live_aqi_data()

# Get live AQI for a specific station and time
aqi <- cpcb_get_live_aqi_data(
  station_id = "site_103",
  date       = "2024-01-15",
  hour       = 10
)

## End(Not run)

Get live AQI data for a station

Description

Get live AQI data for a specific station at a specific time.

Usage

cpcb_get_live_aqi_data_for_station(station_id, date_time)

Arguments

station_id

Character. Station ID (e.g. "site_103").

date_time

Character. Date and time in "YYYY-MM-DDTHH:00:00Z" format.

Value

List with live AQI data including pollutant readings

Examples

## Not run: 
aqi <- cpcb_get_live_aqi_data_for_station(
  station_id = "site_103",
  date_time  = "2024-01-15T10:00:00Z"
)

## End(Not run)

Find nearest monitoring station

Description

Find nearest CPCB monitoring station to given coordinates. If no coordinates provided, uses IP-based geolocation automatically. Returns station ID, name, and distance in kilometres.

Usage

cpcb_get_nearest_station(coords = NULL)

Arguments

coords

Optional numeric vector c(lat, lon). If NULL, uses IP location.

Value

List with station_id, station_name, and distance_km

Examples

## Not run: 
# Auto-detect location
nearest <- cpcb_get_nearest_station()
cat(
  "Nearest station:", nearest$station_name,
  "(", round(nearest$distance_km, 1), "km)"
)

# Provide coordinates manually (Mumbai)
nearest <- cpcb_get_nearest_station(coords = c(19.076, 72.877))

## End(Not run)

Get list of states with AQI data

Description

Get list of states available for AQI data from CPCB.

Usage

cpcb_get_state_list()

Value

Character vector of state names

Examples

## Not run: 
states <- cpcb_get_state_list()
head(states)

## End(Not run)

Get station list for a city

Description

Get station list available in given city from CPCB.

Usage

cpcb_get_station_list(city)

Arguments

city

Character. City name (e.g. "Delhi", "Mumbai").

Value

Data frame with columns value (station ID) and label (station name)

Examples

## Not run: 
stations <- cpcb_get_station_list("Delhi")
head(stations)

## End(Not run)

Get system location via IP geolocation

Description

Get approximate system location using IP-based geolocation. Returns city-level coordinates based on the machine's public IP address.

Usage

cpcb_get_system_location()

Value

Numeric vector c(lat, lon)

Examples

## Not run: 
loc <- cpcb_get_system_location()
cat("Latitude:", loc["lat"], "Longitude:", loc["lon"])

## End(Not run)

Vectorized AQI category

Description

Convert vector of AQI values to categories

Usage

get_aqi_categories(aqi_values)

Arguments

aqi_values

Numeric vector of AQI values

Value

Character vector of AQI categories


Get AQI category

Description

Convert AQI numeric value to category

Usage

get_aqi_category(aqi_value)

Arguments

aqi_value

Numeric AQI value

Value

AQI category string


Calculate haversine distance

Description

Calculate great circle distance between two points

Usage

haversine_distance(lat1, lon1, lat2, lon2)

Arguments

lat1

Latitude of first point

lon1

Longitude of first point

lat2

Latitude of second point

lon2

Longitude of second point

Value

Distance in kilometers


Find the nearest stations between two sets of points

Description

For every row in from (e.g. low-cost sensors), find the k closest rows in to (e.g. reference stations) by haversine distance. Useful for pairing sensor networks for calibration or cross-validation.

Usage

nearest_stations(from, to, k = 1, from_id = "id", to_id = "id")

Arguments

from

Data frame of source points. Must contain lat/lon.

to

Data frame of candidate target points. Must contain lat/lon.

k

Integer number of nearest targets to return per source point.

from_id, to_id

Column names identifying each point, carried into the output as from_id/to_id.

Value

A data frame with one row per (source, nearest target) pair: from_id, to_id, rank (1 = closest), and dist_km.

Examples

## Not run: 
nearest_stations(airnet, cpcb, k = 3, from_id = "id", to_id = "id")

## End(Not run)

Fetch monthly station data for a provider across one or more months

Description

Pulls the station list for provider, optionally restricts it to one or more cities, then fetches monthly aggregates for every station across the requested months. Returns a single tidy data frame with station metadata (id, name, lat, lon) joined to each daily record. Stations that return no data for a month are skipped.

Usage

oaq_fetch_monthly_stations(
  session,
  provider,
  year,
  months = sprintf("%02d", 1:12),
  city = NULL
)

Arguments

session

List returned by oaq_session.

provider

Character provider id (e.g. "cpcb", "airnet").

year

Integer year (e.g. 2026).

months

Character vector of zero-padded months (e.g. c("03", "04")). Defaults to all twelve months.

city

Optional character vector of city names to keep (matched against the station list's city column). NULL keeps every city.

Value

A data frame of daily records with station_id, date, the pollutant columns returned by the API, and lat/lon/ name from the station list.

Examples

## Not run: 
session <- oaq_session()
blr <- oaq_fetch_monthly_stations(
  session, "airnet",
  year = 2026, months = c("03", "04"), city = "Bengaluru"
)

## End(Not run)

Get annual aggregated data for a sensor

Description

Retrieve annual aggregated air quality data for a specific sensor and year.

Usage

oaq_get_annual(session, provider, sensor_id, year)

Arguments

session

List returned by oaq_session().

provider

Character. Provider name (e.g. "AURASSURE").

sensor_id

Character. Sensor station ID.

year

Integer or character. Year (e.g. 2024).

Value

Parsed annual aggregate record.

Examples

## Not run: 
session <- oaq_session()
annual <- oaq_get_annual(session, "AURASSURE", "sensor_001", 2024)

## End(Not run)

Get latest AQI for a city

Description

Get the latest air quality map readings for all sensors in a city.

Usage

oaq_get_city_latest(session, provider, city)

Arguments

session

List returned by oaq_session().

provider

Character. Provider name (e.g. "AURASSURE").

city

Character. City name as it appears in the provider hierarchy.

Value

Parsed list of sensor readings for the city.

Examples

## Not run: 
session <- oaq_session()
latest <- oaq_get_city_latest(session, "AURASSURE", "Bengaluru")

## End(Not run)

Get daily historical data for a sensor

Description

Retrieve daily aggregated air quality data for a specific sensor, date.

Usage

oaq_get_daily(session, provider, sensor_id, year, month, day)

Arguments

session

List returned by oaq_session().

provider

Character. Provider name (e.g. "AURASSURE").

sensor_id

Character. Sensor station ID.

year

Integer or character. Year (e.g. 2024).

month

Integer or character. Month (1–12).

day

Integer or character. Day of month (1–31).

Value

Parsed daily data record.

Examples

## Not run: 
session <- oaq_session()
daily <- oaq_get_daily(session, "AURASSURE", "sensor_001", 2024, 1, 15)

## End(Not run)

Get provider geographic hierarchy

Description

Get the Country > City > Sensor geographical tree for a data provider.

Usage

oaq_get_hierarchy(session, provider)

Arguments

session

List returned by oaq_session().

provider

Character. Provider name (e.g. "AURASSURE").

Value

Parsed hierarchy list.

Examples

## Not run: 
session <- oaq_session()
hierarchy <- oaq_get_hierarchy(session, "AURASSURE")

## End(Not run)

Get monthly aggregated data for a sensor

Description

Retrieve monthly aggregated air quality data for a specific sensor and month.

Usage

oaq_get_monthly(session, provider, sensor_id, year, month)

Arguments

session

List returned by oaq_session().

provider

Character. Provider name (e.g. "AURASSURE").

sensor_id

Character. Sensor station ID.

year

Integer or character. Year (e.g. 2024).

month

Integer or character. Month (1–12).

Value

Parsed monthly aggregate record.

Examples

## Not run: 
session <- oaq_session()
monthly <- oaq_get_monthly(session, "AURASSURE", "sensor_001", 2024, 1)

## End(Not run)

Get last 24 hours of data for a sensor

Description

Retrieve the last 24 hours of readings for a specific sensor station.

Usage

oaq_get_station_24h(session, provider, sensor_id)

Arguments

session

List returned by oaq_session().

provider

Character. Provider name (e.g. "AURASSURE").

sensor_id

Character. Sensor station ID.

Value

Parsed list of hourly readings.

Examples

## Not run: 
session <- oaq_session()
data <- oaq_get_station_24h(session, "AURASSURE", "sensor_001")

## End(Not run)

Get latest readings from all stations

Description

Get the latest sensor readings from all monitoring stations under a provider.

Usage

oaq_get_stations_latest(session, provider)

Arguments

session

List returned by oaq_session().

provider

Character. Provider name (e.g. "AURASSURE").

Value

Parsed list of station-level latest readings.

Examples

## Not run: 
session <- oaq_session()
stations <- oaq_get_stations_latest(session, "AURASSURE")

## End(Not run)

List all OAQ data providers

Description

Retrieve the list of all available data providers on the OAQ platform, including their IDs, display names, and data attribution.

Usage

oaq_list_providers(session)

Arguments

session

List returned by oaq_session().

Value

List with a providers element containing id, name, and attribution for each provider.

Examples

## Not run: 
session <- oaq_session()
providers <- oaq_list_providers(session)
sapply(providers$providers, `[[`, "id")

## End(Not run)

Establish an OAQ API session

Description

Performs the OAQ 2-step handshake: calls the Data Broker with your API key and returns the signed-URL parameters needed for all subsequent data requests. Sessions are valid for 24 hours.

The API key is read from the OAQ_API_KEY environment variable if api_key is not supplied.

Usage

oaq_session(api_key = Sys.getenv("OAQ_API_KEY"))

Arguments

api_key

Character. Your OAQ API key. Defaults to Sys.getenv("OAQ_API_KEY").

Value

Named list with base_url and sig_string (the full query-string to append to every data URL).

Examples

## Not run: 
session <- oaq_session()

## End(Not run)

Clear PM2.5 cache

Description

Delete all cached NetCDF files from the cache directory to free disk space.

Usage

pm25_clear_cache(cache_dir = "pm25_data")

Arguments

cache_dir

Character. Directory containing cached files. Default: "pm25_data".

Value

Invisibly returns NULL.

Examples

## Not run: 
pm25_clear_cache()

## End(Not run)

Download PM2.5 NetCDF file

Description

Download a WUSTL ACAG V6GL02 NetCDF file from AWS S3 and cache it locally. If the file is already cached and complete (>1 MB), the cached version is returned without re-downloading.

Usage

pm25_download_netcdf(
  year,
  month = NULL,
  cache_dir = "pm25_data",
  force_download = FALSE
)

Arguments

year

Integer. Year for data (e.g. 2023).

month

Optional integer (1–12). If NULL, downloads the annual file.

cache_dir

Character. Directory to cache NetCDF files. Default: "pm25_data".

force_download

Logical. Force re-download even if file exists. Default: FALSE.

Value

Character. Path to the downloaded (or cached) NetCDF file.

Examples

## Not run: 
# Download monthly data
nc_path <- pm25_download_netcdf(year = 2023, month = 11)

# Download annual data
nc_path <- pm25_download_netcdf(year = 2023)

## End(Not run)

Get PM2.5 statistics for a region

Description

Compute mean, SD, min, max, and pixel count of satellite PM2.5 for a region defined by a GeoJSON file. Optionally group by a column in the GeoJSON (e.g. district name) to return per-group statistics.

Usage

pm25_get_stats(
  geojson_file,
  year = NULL,
  month = NULL,
  cache_dir = "pm25_data",
  group_by = NULL,
  nc_file = NULL
)

Arguments

geojson_file

Character. Path or URL to a GeoJSON file defining the region (remote http(s):// URLs are read directly).

year

Integer. Year of the NetCDF data (e.g. 2023). Ignored when nc_file is supplied.

month

Optional integer (1–12). If NULL, uses annual data. Ignored when nc_file is supplied.

cache_dir

Character. Directory to cache NetCDF files. Default: "pm25_data".

group_by

Optional character. Column name(s) in the GeoJSON to group polygons by (comma-separated for multiple columns).

nc_file

Optional character. Path to a local NetCDF file to use directly. When supplied, no download is attempted and year/ month are ignored. Useful for offline data (e.g. WUSTL V5GL04 files on a local mount).

Value

List (or data frame if group_by is specified) with PM2.5 statistics: mean, std, min, max, count.

Examples

## Not run: 
# Single region (remote BharatViz boundary)
stats <- pm25_get_stats(
  "https://geo.bharatviz.org/geojsons/cities/delhi.geojson",
  year = 2023, month = 11
)
cat("Mean PM2.5:", round(stats$mean, 1), "ug/m3")

# Grouped by district
stats_by_district <- pm25_get_stats(
  "https://geo.bharatviz.org/geojsons/districts/India_LGD_districts.geojson",
  year     = 2023,
  month    = 11,
  group_by = "district_name"
)

# Use a local (offline) NetCDF file directly
stats <- pm25_get_stats(
  "https://geo.bharatviz.org/geojsons/cities/delhi.geojson",
  nc_file = "V5GL04.HybridPM25.Global.202211-202211.nc"
)

## End(Not run)

List cached PM2.5 NetCDF files

Description

List all cached NetCDF files in the cache directory with file sizes.

Usage

pm25_list_cached_files(cache_dir = "pm25_data")

Arguments

cache_dir

Character. Directory containing cached files. Default: "pm25_data".

Value

Character vector of cached file paths.

Examples

## Not run: 
files <- pm25_list_cached_files()

## End(Not run)

Load a gridded PM2.5 raster cropped to a region's bounding box

Description

Reads the pixels covering shape's bounding box and returns them as a terra raster in EPSG:4326, ready for masking or zonal extraction.

Usage

pm25_load_netcdf_bbox(
  nc_path,
  shape,
  var = "GWRPM25",
  lon_name = "lon",
  lat_name = "lat"
)

Arguments

nc_path

Path to a gridded PM2.5 NetCDF file.

shape

An sf object defining the region.

var

NetCDF variable name. Defaults to "GWRPM25" (WUSTL V5GL04).

lon_name, lat_name

Longitude/latitude dimension names.

Value

A terra SpatRaster cropped to the bounding box.

Examples

## Not run: 
shape <- sf::st_read("https://geo.bharatviz.org/geojsons/cities/delhi.geojson")
r <- pm25_load_netcdf_bbox(pm25_v5gl04_path(2022, 11, "."), shape)

## End(Not run)

Mean gridded PM2.5 over a region's bounding box

Description

Reads only the pixels covering shape's bounding box and returns the mean value. Useful for a quick monthly figure over a city or district.

Usage

pm25_read_netcdf_bbox(
  nc_path,
  shape,
  var = "GWRPM25",
  lon_name = "lon",
  lat_name = "lat"
)

Arguments

nc_path

Path to a gridded PM2.5 NetCDF file.

shape

An sf object defining the region.

var

NetCDF variable name. Defaults to "GWRPM25" (WUSTL V5GL04).

lon_name, lat_name

Longitude/latitude dimension names.

Value

Numeric mean value over the bounding box.

Examples

## Not run: 
shape <- sf::st_read("https://geo.bharatviz.org/geojsons/cities/delhi.geojson")
pm25_read_netcdf_bbox(pm25_v5gl04_path(2022, 11, "."), shape)

## End(Not run)

Build the file path for a WUSTL V5GL04 monthly NetCDF

Description

Build the file path for a WUSTL V5GL04 monthly NetCDF

Usage

pm25_v5gl04_path(year, month, base_dir)

Arguments

year

Integer year (1998–2022).

month

Integer month (1–12).

base_dir

Directory holding the monthly NetCDF files.

Value

Character path to the monthly NetCDF file.

Examples

pm25_v5gl04_path(2022, 11, base_dir = "~/data/V5GL04/Monthly")

Convert station data to data frame

Description

Convert nested station data to a flat data frame with geographic information, AQI values, and categories. This is the primary way to get station coordinates (latitude/longitude) from live CPCB data.

Usage

stations_to_dataframe(data)

Arguments

data

List of cities with nested stations (from cpcb_get_all_india())

Value

Data frame with columns: station_id, station_name, city_name, city_id, state_id, longitude, latitude, live, avg_aqi, status, aqi_category


Print vayuayan welcome message

Description

Display package information and usage

Usage

vayuayan_welcome()