knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE, results='hide') options(width = 100)
The first step in using the aWhere API is to create your account and your first app. Doing this will provide you with your key and secret, which are necessary for hitting the various endpoints in the API. Information and steps on creating your account and retreiving your key and secret can be found on the aWhere Developer Portal website here: http://developer.awhere.com/api/get-started. A default key/secret has been provided with this package to get you going but has limited data access and will expire.
library(aWhereAPI) aWhereAPI::load_credentials("credentials_trial.txt") obs_startdate <- as.character(Sys.Date() - 30) obs_enddate <- as.character(Sys.Date() - 1) for_startdate <- as.character(Sys.Date()) for_enddate <- as.character(Sys.Date() + 7) try(aWhereAPI::delete_field(field_id = "1"),silent = TRUE) try(aWhereAPI::delete_field(field_id = "2"),silent = TRUE)
Once you have your account/app set up, you are ready to start using the aWhere API package. To start using the package in your R session, load it using the library(aWhereAPI)
command.
library(aWhereAPI)
Once loaded, he first step when using the R package will always be to request a token using the load_credentials()
function. This function creates a unique token tied to your app, and gives your app authorization to retreive data from the aWhere API. This function points to a text file that contains two strings: your key and your secret each on separate lines. There must also be one blank line afterward. aWhere API tokens expire after one hour, however after the first time running the get_token()
function in a given R session, the R package will automatically handle getting a new token upon expiration.
aWhereAPI::load_credentials("credentials_trial.txt")
It is also possible to use the get_token(uid = "ABCDEFG", secret = "123456")
function to similar effect.
aWhereAPI::get_token(uid = "ABCDEFG", secret = "123456")
The aWhere API offers many different endpoints to accessing a variety of agronomic and weather related information. The first category of endpoints deals with Fields and Plantings. In these endpoints users store specific fields and associated agronomic planting information and retrieve information using the names associated with each field activity/named field. More specifically, fields are objects tied to your app that contain extra information besides a simple latitude/longitude. Latitude and longitude are of course included, but only when initially creating the Field. Creating a Field allows the user to include information such as the name, farmid, and the size of the field. More information on the Fields endpoint can be found here: http://developer.awhere.com/api/reference/fields-plantings.
There are two ways of specifying a location when using the aWhere API. The first way is using latitude and longitude information that can be passed directly to the API to return data for the specific location.
Using the aWhere R package to create a field is extremely simple and can be done using the create_field()
function. For example: create_field(field_id = "1", latitude = 40, longitude = -90, farm_id = "My Farm", field_name = "Field 1", acres = 30)
. Creating a field with the information you specify will make your field accessible through many different API endpoints.
aWhereAPI::create_field(field_id = "1", latitude = 40, longitude = -90, farm_id = "My Farm", field_name = "Field 1", acres = 30) aWhereAPI::create_field(field_id = "2", latitude = 40, longitude = -90, farm_id = "My Other Farm", field_name = "Field A", acres = 35)
Once you have created a field in the API, you can easily return the information associated with that field. Or, if you have multiple fields a list of all fields associated with your account can also be returned. To return a list of fields use the get_fields()
function either running it without passing any parameters to get all fields associated with your account, or passing in the field_id of the single field you'd like to get information on. For example: get_fields()
will return all fields, while get_fields(field_id = "1")
will return only the information about field_id "1".
aWhereAPI::get_fields() aWhereAPI::get_fields(field_id = "1")
Once a field has been created, it is possible to update some of the field's data, specifically the name or farmid. To update either one of these, use the update_field()
function. For example: update_field(field_id = "1", variable_update = "name", value_update = "Old Field 1")
.
aWhereAPI::update_field(field_id = "1", variable_update = "name", value_update = "Old Field 1") aWhereAPI::get_fields(field_id = "1")
If for some reason you need to delete a field from your account, you are able to do so using the delete_field()
function. To do so, simply pass in the field_id of the field you wish to delete: delete_field(field_id = "1")
aWhereAPI::delete_field(field_id = "1") aWhereAPI::get_fields()
The group of aWhere Weather API endpoints allows the user access to aWhere's unique weather dataset including daily observations, long-term normals, and forecast data. The Weather endpoints can be accessed either by latitude/longitude coordinates or by using the Fields associated with a user's account. The API R package provides separate functions for field-based requests and location-based requests. It is important to make sure you are using the correct one, otherwise you will run into errors when requesting data.
The daily observations endpoint allows weather data retrieval for the past 30 months of data for a variety of important weather attributes. These include maximum and minimum temperature, precipitation amount, solar radiation, maximum and minimum relative humidity, and morning maximum, daily maximum, and daily mean wind speeds. Measurement are returned in metric units. More information on the daily weather observations endpoint can be found here: http://developer.awhere.com/api/reference/weather/observations.
The relevant R functions for the daily observed weather data are: daily_observed_latlng()
and daily_observed_fields()
. Both of these functions require a specified start date and end date for the data you wish to pull. The location-based function will also require a latitude and longitude coordinate, while the fields-based function will require a valid field_id. Possible function calls to retrieve data for the last 30 days would take the following forms:
daily_observed_latlng(latitude = 40, longitude = -90, day_start = "`r obs_startdate`", day_end = "`r obs_enddate`")
daily_observed_fields(field_id = "1", day_start = "`r obs_startdate`", day_end = "`r obs_enddate`")
obs_startdate <- as.character(Sys.Date() - 30) obs_enddate <- as.character(Sys.Date() - 1) observed <- aWhereAPI::daily_observed_latlng(latitude = 40, longitude = -90, day_start = obs_startdate, day_end = obs_enddate) # take a look at the first 6 rows of location, date, and temperature data head(observed[,c('latitude', 'longitude', 'date', 'temperatures.min','temperatures.max')])
In addition to daily weather observations, aWhere also provides access to weather forecasts up to 7 days into the future. Forecast data is broken into forecast blocks and the temporal length of these blocks can be specified by the user. Simply put, the block size is the number of hours of data included in a single record of data. In order to retrieve daily forecasts, the block size will be set to 24. Hourly forecasts can also be retrieved by using a block size of 1. The different block sizes available are 1, 2, 3, 4, 6, 8, 12, and 24. More information on the forecast endpoint can be found here: http://developer.awhere.com/api/reference/weather/forecast.
Forecast data includes many different attributes: forecasted text weather conditions (e.g. "Sunny Day", "Clear Night"), temperatures, precipitation chance and amount, cloud cover, sunshine, solar radiation, maximum and minimum relative humidity, dew point, and mean, maximum, and minimum wind speeds. Like the observed data, there are two different R functions for retrieving forecast data, one for locations and one for fields.
To retrieve the daily forecast data for the next 7 days (8 if you'd like to include the current date), R function calls should follow these formats:
forecasts_latlng(latitude = 40, longitude = -90, day_start = "`r for_startdate`", day_end = "`r for_enddate`", block_size = 24)
forecasts_fields(field_id = "1", day_start = "`r for_startdate`", day_end = "`r for_enddate`", block_size = 24)
.
for_startdate <- as.character(Sys.Date()) for_enddate <- as.character(Sys.Date() + 7) dailyforecast <- aWhereAPI::forecasts_latlng(latitude = 40, longitude = -90, day_start = for_startdate, day_end = for_enddate, block_size = 24) # take a look at the first 6 rows of the daily forecast location, # starting/ending times, and sky cloud cover data head(dailyforecast[,c('latitude','longitude', 'startTime','endTime','sky.cloudCover')])
Hourly forecast data could be retrieved by changing the block_size parameter to 1 instead of 24:
forecasts_latlng(latitude = 40, longitude = -90, day_start = "`r for_startdate`", day_end = "`r for_enddate`", block_size = 1)
hourlyforecast <- aWhereAPI::forecasts_latlng(latitude = 40, longitude = -90, day_start = for_startdate, day_end = for_enddate, block_size = 1) # take a look at the first 6 rows of the hourly forecast location, # starting/ending times, and sky cloud cover data head(hourlyforecast[,c('latitude','longitude', 'startTime','endTime','sky.cloudCover')])
To provide a longer date range of access to our historical weather data, the Historical Weather Norms API endpoint returns averages and standard deviations of our weather attributes. These values are useful for comparing recent weather events and data to their long-term averages. Using the Weather Norms endpoint requires a slightly different use of dates when retrieving data. Rather than passing in a date, e.g. "2018-06-30", we pass in month and day combinations, e.g. "06-30". Using this in the relevant R functions is how a user would return the long-term normals for June 30th.
Like the two above endpoints, the weather norms data has a location-based function, weather_norms_latlng()
and a field-based function, weather_norms_fields()
. There are also two parameters that must be included in the function call: year_start and year_end. These two parameters are used to specify the range of years you would like included in the long-term normals calculations. You must have at least 3 years included to run the calculations. Examples of the two are as follows:
weather_norms_latlng(latitude = 40, longitude = -90, monthday_start = "06-01", monthday_end = "06-30", year_start = 2006, year_end = 2017)
weather_norms_fields(field_id = "1", monthday_start = "06-01", monthday_end = "06-30", year_start = 2006, year_end = 2017)
.
norms <- aWhereAPI::weather_norms_latlng(latitude = 40, longitude = -90, monthday_start = "06-01", monthday_end = "06-30", year_start = 2006, year_end = 2017) # take a look at the first 6 rows of the long-term normal data # location, date, max precipitation, and average precipitation head(norms[,c('latitude','longitude','day', 'maxTemp.average','precipitation.average')])
If you would like to save data that you've pulled from the aWhere API and either continue to use it in R, or export it and use it in another program outside of R, we'll need to assign the data from the API to an R variable:
Using a variable name, in this case observed
, and R's assignment operator <-
, we can assign the data from the API call into this new variable like so:
observed <- daily_observed_latlng(latitude = 40, longitude = -90, day_start = "`r obs_startdate`", day_end = "`r obs_enddate`")
.
Now we can simply reference the observed
variable to perform operations on the data or to simply see what it looks like:
# take a look at the first 6 rows of location, date, and temperature data head(observed[,c('latitude', 'longitude', 'date', 'temperatures.min','temperatures.max')])
Assigning data you pull from the API to a variable within R will keep you from having to requery the API in your analyses.
Now that we have data in this observed
variable, we can also use it to save the data to a variety of different formats. A comprehensive guide to importing and exporting data with R can be found here: https://cran.r-project.org/doc/manuals/r-release/R-data.pdf.
We'll use a CSV (comma-separated values) file for our export example. CSV files are extremely common and can be easily handled by most applications. To save our observed data into an CSV file the following command will work, substituting in your file path:
write.csv(observed, file = "/path/to/file/observed.csv", row.names = F)
.
write.csv(observed, file = "testFile.csv", row.names = F)
Now that the data has been saved to a CSV, we can read it back in just as easily:
obs_csv <- read.csv(file = "testFile.csv", header = T, stringsAsFactors = FALSE)
To make sure the two data frames are equal, we can take a look at the top few rows for each of them:
# take a look at the first 6 rows of location, date, and temperature # for the orignal data frame head(observed[,c('latitude', 'longitude', 'date', 'temperatures.min','temperatures.max')]) # for the CSV data head(obs_csv[,c('latitude', 'longitude', 'date', 'temperatures.min','temperatures.max')])
You can also use the all.equal
function to see if the two data frames are equivalent:
all.equal(observed, obs_csv)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.