Newer
Older
%\VignetteIndexEntry{Introduction to the dataRetrieval package}
%\VignetteSuggests{xtable,EGRET}
%\VignetteImports{zoo, XML, RCurl}
%\VignettePackage{dataRetrieval}
\documentclass[a4paper,11pt]{article}
\usepackage{amsmath}
\usepackage{times}
\usepackage{hyperref}
\usepackage[numbers, round]{natbib}
\usepackage[american]{babel}
\usepackage{authblk}
\usepackage{footnote}
\usepackage{tabularx}
\usepackage{threeparttable}
\usepackage{parskip}
\renewcommand\Affilfont{\itshape\small}
\renewcommand{\topfraction}{0.85}
\renewcommand{\textfraction}{0.1}
\usepackage{graphicx}
\textwidth=6.2in
\textheight=8.5in
\parskip=.3cm
\oddsidemargin=.1in
\evensidemargin=.1in
\headheight=-.3in
%------------------------------------------------------------
% newcommand
%------------------------------------------------------------
\newcommand{\scscst}{\scriptscriptstyle}
\newcommand{\scst}{\scriptstyle}
\newcommand{\Robject}[1]{{\texttt{#1}}}
\newcommand{\Rfunction}[1]{{\texttt{#1}}}
\newcommand{\Rclass}[1]{\textit{#1}}
\newcommand{\Rpackage}[1]{\textit{#1}}
\newcommand{\Rexpression}[1]{\texttt{#1}}
\newcommand{\Rmethod}[1]{{\texttt{#1}}}
\newcommand{\Rfunarg}[1]{{\texttt{#1}}}
\begin{document}
<<openLibrary, echo=FALSE>>=
library(xtable)
options(continue=" ")
options(width=60)
library(knitr)
@
%------------------------------------------------------------
\title{The dataRetrieval R package}
%------------------------------------------------------------
\author[1]{Laura De Cicco}
\author[1]{Robert Hirsch}
\affil[1]{United States Geological Survey}
<<include=TRUE ,echo=FALSE,eval=TRUE>>=
opts_chunk$set(highlight=TRUE, tidy=TRUE, keep.space=TRUE, keep.blank.space=FALSE, keep.comment=TRUE, tidy=FALSE,comment="")
knit_hooks$set(inline = function(x) {
if (is.numeric(x)) round(x, 3)})
knit_hooks$set(crop = hook_pdfcrop)
@
\maketitle
\tableofcontents
%------------------------------------------------------------
\section{Introduction to dataRetrieval}
%------------------------------------------------------------
The dataRetrieval package was created to simplify the process of loading hydrology data into the R environment. It has been specifically designed to work seamlessly with the EGRET R package: Exploration and Graphics for RivEr Trends. See: \url{https://github.com/USGS-R/EGRET/wiki} for information on EGRET. EGRET is designed to provide analysis of water quality data sets using the Weighted Regressions on Time, Discharge and Season (WRTDS) method as well as analysis of discharge trends using robust time-series smoothing techniques. Both of these capabilities provide both tabular and graphical analyses of long-term data sets.
The dataRetrieval package is designed to retrieve many of the major data types of United States Geological Survey (USGS) hydrology data that are available on the web. Users may also load data from other sources (text files, spreadsheets) using dataRetrieval. Section \ref{sec:genRetrievals} provides examples of how one can obtain raw data from USGS sources on the web and ingest them into data frames within the R environment. The functionality described in section \ref{sec:genRetrievals} is for general use and is not tailored for the specific uses of the EGRET package. The functionality described in section \ref{sec:EGRETdfs} is tailored specifically to obtaining input from the web and structuring it for use in the EGRET package. The functionality described in section \ref{sec:summary} is for converting hydrology data from user-supplied files and structuring it specifically for use in the EGRET package.
For information on getting started in R and installing the package, see (\ref{sec:appendix1}): Getting Started.
Quick workflow for major dataRetrieval functions:
<<workflow, echo=TRUE,eval=FALSE>>=
library(dataRetrieval)
# Site ID for Choptank River near Greensboro, MD
siteNumber <- "01491000"
ChoptankInfo <- getSiteFileData(siteNumber)
parameterCd <- "00060"
rawDailyData <- retrieveNWISData(siteNumber,parameterCd,
"1980-01-01","2010-01-01")
Daily <- getDVData(siteNumber,parameterCd,
"1980-01-01","2010-01-01")
# Sample data Nitrate:
parameterCd <- "00618"
Sample <- getSampleData(siteNumber,parameterCd,
"1980-01-01","2010-01-01")
# Metadata on site and nitrate:
INFO <- getMetaData(siteNumber,parameterCd)
# Merge discharge and nitrate data to one dataframe:
Sample <- mergeReport()
%------------------------------------------------------------
\section{General USGS Web Retrievals}
%------------------------------------------------------------
In this section, we will run through 5 examples, which document how to get raw data from the web. This data includes site information (\ref{sec:usgsSite}), measured parameter information (\ref{sec:usgsParams}), historical daily values(\ref{sec:usgsDaily}), unit values (which include real-time data but can also include other sensor data stored at regular time intervals) (\ref{sec:usgsRT}), and water quality data (\ref{sec:usgsWQP}) or (\ref{sec:usgsSTORET}). We will use the Choptank River near Greensboro, MD as an example. The site-ID for this gage station is 01491000. Daily discharge measurements are available as far back as 1948. Additionally, nitrate has been measured dating back to 1964. The functions/examples in this section are for raw data retrieval. In the next section, we will use functions that retrieve and process the data in a dataframe that may prove friendier for R analysis, and is specifically tailored to EGRET analysis.
%------------------------------------------------------------
\subsection{Introduction}
%------------------------------------------------------------
The USGS organizes their hydrology data in a standard structure. Streamgages are located throughout the United States, and each streamgage has a unique ID. Often (but not always), these ID's are 8 digits. The first step to finding data is discovering this 8-digit ID. There are many ways to do this, one is the National Water Information System: Mapper \url{http://maps.waterdata.usgs.gov/mapper/index.html}.
Once the site-ID is known, the next required input for USGS data retrievals is the `parameter code'. This is a 5-digit code that specifies what measured parameter is being requested. For example, parameter code 00631 represents `Nitrate plus nitrite, water, filtered, milligrams per liter as nitrogen', with units of `mg/l as N'. A complete list of possible USGS parameter codes can be found at \url{http://go.usa.gov/bVDz}.
Not every station will measure all parameters. A short list of commonly measured parameters is shown in Table \ref{tab:params}.
<<tableParameterCodes, echo=FALSE,results='asis'>>=
pCode <- c('00060', '00065', '00010','00045','00400')
shortName <- c("Discharge [cfs]","Gage height [ft]","Temperature [C]", "Precipitation [in]", "pH")
data.df <- data.frame(pCode, shortName, stringsAsFactors=FALSE)
caption="Common USGS Parameter Codes")
A complete list (as of September 25, 2013) is available as data attached to the package. It can be accessed by the following:
<<tableParameterCodesDataRetrieval>>=
library(dataRetrieval)
parameterCdFile <- parameterCdFile
names(parameterCdFile)
# Sorting out some common values:
subset(parameterCdFile,parameter_cd %in% c("00060","00010","00400"))
@
For unit values data (sensor data), knowing the parameter code and site ID is enough to make a request for data. For most variables that are measured on a continuous basis, the USGS also stores the historical data as daily values. These daily values are statistical summaries of the continuous data, e.g. maximum, minimum, mean, median. The different statistics are specified by a 5-digit statistics code. A complete list of statistic codes can be found here:
\url{http://nwis.waterdata.usgs.gov/nwis/help/?read_file=stat&format=table}
Some common codes are shown in Table \ref{tab:stat}.
<<tableStatCodes, echo=FALSE,results='asis'>>=
StatCode <- c('00001', '00002', '00003','00008')
shortName <- c("Maximum","Minimum","Mean", "Median")
data.df <- data.frame(StatCode, shortName, stringsAsFactors=FALSE)
Examples for using these site ID's, parameter codes, and stat codes will be presented in subsequent sections.
%------------------------------------------------------------
\subsection{Site Information}
\label{sec:usgsSite}
%------------------------------------------------------------
%------------------------------------------------------------
\subsubsection{getSiteFileData}
\label{sec:usgsSiteFileData}
%------------------------------------------------------------
Use the getSiteFileData function to obtain all of the information available for a particular USGS site such as full station name, drainage area, latitude, and longitude:
# Site ID for Choptank River near Greensboro, MD
siteNumber <- "01491000"
ChoptankInfo <- getSiteFileData(siteNumber)
@
Pulling out a specific example piece of information, in this case station name can be done as follows:
ChoptankInfo$station.nm
@
Site information is obtained from \url{http://waterservices.usgs.gov/rest/Site-Test-Tool.html}
\FloatBarrier
%------------------------------------------------------------
\subsubsection{getDataAvailability}
\label{sec:usgsDataAvailability}
%------------------------------------------------------------
To discover what data is available for a particular USGS site, including measured parameters, period of record, and number of samples (count), use the getDataAvailability function. It is possible to limit the retrieval information to a subset of variables. In the following example, we limit the retrieved Choptank data to only daily mean parameter (excluding all unit value and water quality values).
# Continuing from the previous example:
# This pulls out just the daily data:
ChoptankAvailableData <- getDataAvailability(siteNumber)
ChoptankDailyData <- subset(ChoptankAvailableData,
"dv" == service)
# This pulls out the mean:
ChoptankDailyData <- subset(ChoptankDailyData,
"00003" == statCd)
tableData <- with(ChoptankDailyData,
data.frame( srsname=srsname,
startDate=as.character(startDate),
endDate=as.character(endDate),
count=as.character(count),
units=parameter_units)
caption="Daily mean data availabile at the Choptank River near Greensboro, MD. Some columns deleted for space considerations.")
See Section \ref{app:createWordTable} for instructions on converting an R dataframe to a table in Microsoft Excel or Word to display a data availability table similar to Table \ref{tab:gda}.
%------------------------------------------------------------
\subsection{Parameter Information}
\label{sec:usgsParams}
%------------------------------------------------------------
To obtain all of the available information concerning a measured parameter, use the getParameterInfo function:
# Using defaults:
parameterCd <- "00618"
parameterINFO <- getParameterInfo(parameterCd)
colnames(parameterINFO)
@
Pulling out a specific example piece of information, in this case parameter name can be done as follows:
<<siteNames, echo=TRUE>>=
parameterINFO$parameter_nm
@
Parameter information is obtained from \url{http://nwis.waterdata.usgs.gov/nwis/pmcodes/}
\FloatBarrier
%------------------------------------------------------------
\subsection{Daily Values}
\label{sec:usgsDaily}
%------------------------------------------------------------
To obtain daily records of USGS data, use the retrieveNWISData function. The arguments for this function are siteNumber, parameterCd, startDate, endDate, statCd, and a logical (TRUE/FALSE) interactive. There are 2 default arguments: statCd (defaults to \texttt{"}00003\texttt{"}), and interactive (defaults to TRUE). If you want to use the default values, you do not need to list them in the function call. Setting the \texttt{"}interactive\texttt{"} option to TRUE will walk you through the function. It might make more sense to run large batch collections with the interactive option set to FALSE.
The dates (start and end) need to be in the format \texttt{"}YYYY-MM-DD\texttt{"} (note: the user does need to include the quotes). Setting the start date to \texttt{"}\texttt{"} (no space) will indicate to the program to ask for the earliest date, setting the end date to \texttt{"}\texttt{"} (no space) will ask for the latest available date.
<<label=getNWISDaily, echo=TRUE, eval=TRUE>>=
# Continuing with our Choptank River example
parameterCd <- "00060" # Discharge (cfs)
startDate <- "" # Will request earliest date
endDate <- "" # Will request latest date
discharge <- retrieveNWISData(siteNumber,
parameterCd, startDate, endDate)
The column `datetime' in the returned dataframe is automatically imported as a variable of class `Date' in R. Each requested parameter has a value and remark code column. The names of these columns depend on the requested parameter and stat code combinations. USGS remark codes are often `A' (approved for publication) or `P' (provisional data subject to revision). A more complete list of remark codes can be found here:
\url{http://waterdata.usgs.gov/usa/nwis/help?codes_help}
Another example that doesn't use the defaults would be a request for mean and maximum daily temperature and discharge in early 2012:
<<label=getNWIStemperature, echo=TRUE>>=
parameterCd <- c("00010","00060") # Temperature and discharge
statCd <- c("00001","00003") # Mean and maximum
startDate <- "2012-01-01"
temperatureAndFlow <- retrieveNWISData(siteNumber, parameterCd,
@
Daily data is pulled from \url{http://waterservices.usgs.gov/rest/DV-Test-Tool.html}.
The column names can be automatically adjusted based on the parameter and statistic codes using the renameColumns function. This is not necessary, but may be useful when analyzing the data.
<<label=renameColumns, echo=TRUE>>=
names(temperatureAndFlow)
temperatureAndFlow <- renameColumns(temperatureAndFlow)
names(temperatureAndFlow)
@
An example of plotting the above data (Figure \ref{fig:getNWIStemperaturePlot}):
<<getNWIStemperaturePlot, echo=TRUE, fig.cap="Temperature and discharge plot of Choptank River in 2012.",out.width='1\\linewidth',out.height='1\\linewidth',fig.show='hold'>>=
par(mar=c(5,5,5,5)) #sets the size of the plot window
with(temperatureAndFlow, plot(
Laura A DeCicco
committed
datetime, Temperature_water_degrees_Celsius_Max_01,
))
par(new=TRUE)
with(temperatureAndFlow, plot(
Laura A DeCicco
committed
datetime, Discharge_cubic_feet_per_second,
col="red",type="l",xaxt="n",yaxt="n",xlab="",ylab="",axes=FALSE
))
axis(4,col="red",col.axis="red")
title(paste(ChoptankInfo$station.nm,"2012",sep=" "))
legend("topleft", c("Max Temperature", "Mean Discharge"),
col=c("black","red"),lty=c(NA,1),pch=c(1,NA))
There are occasions where NWIS values are not reported as numbers, instead there might be text describing a certain event such as `Ice'. Any value that cannot be converted to a number will be reported as NA in this package (not including remark code columns).
%------------------------------------------------------------
\subsection{Unit Values}
\label{sec:usgsRT}
%------------------------------------------------------------
Any data that are collected at regular time intervals (such as 15-minute or hourly) are known as `unit values'. Many of these are delivered on a real time basis and very recent data (even less than an hour old in many cases) are available through the function retrieveUnitNWISData. Some of these unit values are available for many years, and some are only available for a recent time period such as 120 days. Here is an example of a retrieval of such data.
<<label=getNWISUnit, echo=TRUE>>=
parameterCd <- "00060" # Discharge (cfs)
startDate <- "2012-05-12"
endDate <- "2012-05-13"
dischargeToday <- retrieveUnitNWISData(siteNumber, parameterCd,
startDate, endDate)
@
Which produces the following dataframe:
<<dischargeData, echo=FALSE>>=
head(dischargeToday)
@
Note that time now becomes important, so the variable datetime is a POSIXct, and the time zone is included in a separate column. Data is pulled from \url{http://waterservices.usgs.gov/rest/IV-Test-Tool.html}. There are occasions where NWIS values are not reported as numbers, instead a common example is \texttt{"}Ice\texttt{"}. Any value that cannot be converted to a number will be reported as NA in this package.
\newpage
\FloatBarrier
%------------------------------------------------------------
\subsection{Water Quality Values}
\label{sec:usgsWQP}
%------------------------------------------------------------
To get USGS water quality data from water samples collected at the streamgage (as distinct from unit values collected through some type of automatic monitor) we can use the Water Quality Data Portal: \url{http://www.waterqualitydata.us/}. The raw data are obtained from the function getRawQWData, with the similar input arguments: siteNumber, parameterCd, startDate, endDate, and interactive. The difference is in parameterCd, in this function multiple parameters can be queried using a vector, and setting parameterCd to \texttt{"}\texttt{"} will return all of the measured observations. The raw data may be overwhelming, a simplified version of the data can be obtained using getQWData. There is a large amount of data returned for each observation.
<<label=getQW, echo=TRUE>>=
# Dissolved Nitrate parameter codes:
parameterCd <- c("00618","71851")
startDate <- "1979-10-11"
endDate <- "2012-12-18"
dissolvedNitrate <- getRawQWData(siteNumber, parameterCd,
startDate, endDate)
dissolvedNitrateSimple <- getQWData(siteNumber, parameterCd,
startDate, endDate)
names(dissolvedNitrateSimple)
@
Note that in this dataframe, datetime is imported as Dates (no times are included), and the qualifier is either blank or \texttt{"}\verb@<@\texttt{"} signifying a censored value. A plotting example is shown in Figure \ref{fig:getQWtemperaturePlot}.
<<getQWtemperaturePlot, echo=TRUE, fig.cap="Nitrate plot of Choptank River.">>=
with(dissolvedNitrateSimple, plot(
dateTime, value.00618,
xlab="Date",ylab = paste(parameterINFO$srsname,
"[",parameterINFO$parameter_units,"]")
))
title(ChoptankInfo$station.nm)
@
\FloatBarrier
%------------------------------------------------------------
\subsection{STORET Water Quality Retrievals}
\label{sec:usgsSTORET}
%------------------------------------------------------------
There are additional data sets available on the Water Quality Data Portal (\url{http://www.waterqualitydata.us/}). These data sets can be housed in either the STORET (data from EPA) or NWIS database. Since STORET does not use USGS parameter codes, a `characteristic name' must be supplied. The getWQPData function can retrieve either STORET or NWIS, but requries a characteristic name rather than parameter code. The Water Quality Data Portal includes data discovery tools, and information on characheristic names. The following example retrieves specific conductance from a DNR site in Wisconsin.
<<label=getQWData, echo=TRUE>>=
specificCond <- getWQPData('WIDNR_WQX-10032762',
'Specific conductance', '', '')
head(specificCond)
@
\FloatBarrier
%------------------------------------------------------------
\subsection{URL Construction}
\label{sec:usgsURL}
%------------------------------------------------------------
There may be times when you might be interested in seeing the URL (web address) that was used to obtain the raw data. The constructNWISURL function returns the URL. Aside from input variables that have already been described, there is a new argument \texttt{"}service\texttt{"}. The service argument can be \texttt{"}dv\texttt{"} (daily values), \texttt{"}uv\texttt{"} (unit values), \texttt{"}qw\texttt{"} (NWIS water quality values), or \texttt{"}wqp\texttt{"} (general Water Quality Portal values).
<<label=geturl, echo=TRUE, eval=FALSE>>=
# Dissolved Nitrate parameter codes:
pCode <- c("00618","71851")
startDate <- "1964-06-11"
endDate <- "2012-12-18"
url_qw <- constructNWISURL(siteNumber,pCode,startDate,endDate,'qw')
url_dv <- constructNWISURL(siteNumber,"00060",startDate,endDate,
'dv',statCd="00003")
url_uv <- constructNWISURL(siteNumber,"00060",startDate,endDate,'uv')
@
\FloatBarrier
%------------------------------------------------------------
\section{Data Retrievals Structured For Use In The EGRET Package}
%------------------------------------------------------------
Rather than using the raw data as retrieved by the web, the dataRetrieval package also includes functions that return the data in a structure that has been designed to work with the EGRET R package (\url{https://github.com/USGS-R/EGRET/wiki}). In general, these dataframes may be much more 'R-friendly' than the raw data, and will contain additional date information that allows for efficient data analysis.
In this section, we use 3 dataRetrieval functions to get sufficient data to perform an EGRET analysis. We will continue analyzing the Choptank River. We will be retrieving essentially the same data that were retrieved in the previous section, but in this case it will be structured into three EGRET-specific dataframes. The daily discharge data will be placed in a dataframe called Daily. The nitrate sample data will be placed in a dataframe called Sample. The data about the site and the parameter will be placed in a dataframe called INFO. Although these dataframes were designed to work with the EGRET R package, they can be very useful for a wide range of hydrology studies that don't use EGRET.
%------------------------------------------------------------
\subsection{INFO Data}
%------------------------------------------------------------
The function to obtain metadata, or data about the streamgage and measured parameters is getMetaData. This function combines getSiteFileData and getParameterInfo, producing one dataframe called INFO.
<<ThirdExample>>=
parameterCd <- "00618"
INFO <-getMetaData(siteNumber,parameterCd, interactive=FALSE)
@
\FloatBarrier
%------------------------------------------------------------
\subsection{Daily Data}
%------------------------------------------------------------
The function to obtain the daily values (discharge in this case) is getDVData. It requires the inputs siteNumber, ParameterCd, StartDate, EndDate, interactive, and convert. Most of these arguments are described in the previous section, however `convert' is a new argument (defaults to TRUE). The convert arguement tells the program to convert the values from cubic feet per second (cfs) to cubic meters per second (cms). For EGRET applications with NWIS web retrieval, do not use this argument (the default is TRUE), EGRET assumes that discharge is always in cubic meters per second. If you don't want this conversion and are not using EGRET, set convert=FALSE in the function call.
<<firstExample>>=
siteNumber <- "01491000"
startDate <- "2000-01-01"
endDate <- "2013-01-01"
# This call will get NWIS (cfs) data , and convert it to cms:
Daily <- getDVData(siteNumber, "00060", startDate, endDate)
@
Details of the Daily dataframe are listed below:
<<colNamesDaily, echo=FALSE,results='asis'>>=
ColumnName <- c("Date", "Q", "Julian","Month","Day","DecYear","MonthSeq","Qualifier","i","LogQ","Q7","Q30")
Type <- c("Date", "number", "number","integer","integer","number","integer","string","integer","number","number","number")
Description <- c("Date", "Discharge in cms", "Number of days since January 1, 1850", "Month of the year [1-12]", "Day of the year [1-366]", "Decimal year", "Number of months since January 1, 1850", "Qualifing code", "Index of days, starting with 1", "Natural logarithm of Q", "7 day running average of Q", "30 day running average of Q")
Units <- c("date", "cms","days", "months","days","years","months", "character","days","numeric","cms","cms")
DF <- data.frame(ColumnName,Type,Description,Units)
xtable(DF, caption="Daily dataframe")
If there are discharge values of zero, the code will add a small constant to all of the daily discharges. This constant is 0.001 times the mean discharge. The code will also report on the number of zero and negative values and the size of the constant. EGRET should only be used if the number of zero values is a very small fraction of the total days in the record (say less than 0.1\% of the days), and there are no negative discharge values. Columns Q7 and Q30 are the 7 and 30 day running averages for the 7 or 30 days ending on this specific date.
%------------------------------------------------------------
\subsection{Sample Data}
%------------------------------------------------------------
The function to obtain USGS sample data from the water quality portal is getSampleData. The arguments for this function are also siteNumber, ParameterCd, StartDate, EndDate, interactive. These are the same inputs as getRawQWData or getQWData as described in the previous section.
Sample <-getSampleData(siteNumber,parameterCd,
startDate, endDate)
@
The function to obtain STORET sample data from the water quality portal is getSTORETSampleData. The arguments for this function are siteNumber, characteristicName, StartDate, EndDate, interactive.
<<STORET,echo=TRUE,eval=FALSE>>=
site <- 'WIDNR_WQX-10032762'
characteristicName <- 'Specific conductance'
Sample <-getSTORETSampleData(site,characteristicName,
startDate, endDate)
Details of the Sample dataframe are listed below:
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
% \begin{table}[!ht]
% \begin{minipage}{\linewidth}
% \begin{center}
% \caption{Sample dataframe}
% \begin{tabular}{llll}
% \hline
% ColumnName & Type & Description & Units \\
% \hline
% Date & Date & Date & date \\
% ConcLow & number & Lower limit of concentration & mg/L \\
% ConcHigh & number & Upper limit of concentration & mg/L \\
% Uncen & integer & Uncensored data (1=true, 0=false) & integer \\
% ConcAve & number & Average of ConcLow and ConcHigh & mg/L \\
% Julian & number & Number of days since January 1, 1850 & days \\
% Month & integer & Month of the year [1-12] & months \\
% Day & integer & Day of the year [1-366] & days \\
% DecYear & number & Decimal year & years \\
% MonthSeq & integer & Number of months since January 1, 1850 & months \\
% SinDY & number & Sine of DecYear & numeric \\
% CosDY & number & Cosine of DecYear & numeric \\
% Q \footnotemark[1] & number & Discharge & cms \\
% LogQ \footnotemark[1] & number & Natural logarithm of discharge & numeric \\
% \hline
% \end{tabular}
% \end{center}
% \footnotetext[1]{Discharge columns are populated from data in the Daily dataframe after calling the mergeReport function.}
% \end{minipage}
% \end{table}
\begin{table}
\centering
\begin{threeparttable}[b]
\caption{Sample dataframe}
\label{tab:SampleDataframe}
\begin{tabular}{llll}
\hline
ColumnName & Type & Description & Units \\
\hline
Date & Date & Date & date \\
ConcLow & number & Lower limit of concentration & mg/L \\
ConcHigh & number & Upper limit of concentration & mg/L \\
Uncen & integer & Uncensored data (1=true, 0=false) & integer \\
ConcAve & number & Average of ConcLow and ConcHigh & mg/L \\
Julian & number & Number of days since January 1, 1850 & days \\
Month & integer & Month of the year [1-12] & months \\
Day & integer & Day of the year [1-366] & days \\
DecYear & number & Decimal year & years \\
MonthSeq & integer & Number of months since January 1, 1850 & months \\
SinDY & number & Sine of DecYear & numeric \\
CosDY & number & Cosine of DecYear & numeric \\
Q \tnote{1} & number & Discharge & cms \\
LogQ \tnote{1} & number & Natural logarithm of discharge & numeric \\
\begin{tablenotes}
\item[1] Discharge columns are populated from data in the Daily dataframe after calling the mergeReport function.
\end{tablenotes}
\end{threeparttable}
\end{table}
The next section will talk about summing multiple constituents, including how interval censoring is used. Since the Sample data frame is structured to only contain one constituent, when more than one parameter codes are requested, the getSampleData function will sum the values of each constituent as described below.
%------------------------------------------------------------
\subsection{Censored Values: Summation Explanation}
%------------------------------------------------------------
In the typical case where none of the data are censored (that is, no values are reported as `less-than' values) the ConcLow = ConcHigh = ConcAve all of which are equal to the reported value and Uncen=0. For the most common type of censoring, where a value is reported as less than the reporting limit, then ConcLow = NA, ConcHigh = reporting limit, ConcAve = 0.5 * reporting limit, and Uncen = 1.
As an example to understand how the dataRetrieval package handles a more complex censoring problem, let us say that in 2004 and earlier, we computed total phosphorus (tp) as the sum of dissolved phosphorus (dp) and particulate phosphorus (pp). From 2005 and onward, we have direct measurements of total phosphorus (tp). A small subset of this fictional data looks like Table \ref{tab:exampleComplexQW}.
<<label=tab:exampleComplexQW, echo=FALSE, eval=TRUE,results='asis'>>=
cdate <- c("2003-02-15","2003-06-30","2004-09-15","2005-01-30","2005-05-30","2005-10-30")
rdp <- c("", "<","<","","","")
dp <- c(0.02,0.01,0.005,NA,NA,NA)
rpp <- c("", "","<","","","")
pp <- c(0.5,0.3,0.2,NA,NA,NA)
rtp <- c("","","","","<","<")
tp <- c(NA,NA,NA,0.43,0.05,0.02)
DF <- data.frame(cdate,rdp,dp,rpp,pp,rtp,tp,stringsAsFactors=FALSE)
xtable(DF, caption="Example data",digits=c(0,0,0,3,0,3,0,3),label="tab:exampleComplexQW")
The dataRetrieval package will \texttt{"}add up\texttt{"} all the values in a given row to form the total for that sample when using the Sample dataframe. Thus, you only want to enter data that should be added together. If you want a dataframe with multiple constituents that are not summed, do not use getSampleData, getSTORETSampleData, or getSampleDataFromFile. The raw data functions: getWQPData, retrieveNWISqwData, getRawQWData, getQWData will not sum constituents, but leave them in their individual columns.
For example, we might know the value for dp on 5/30/2005, but we don't want to put it in the table because under the rules of this data set, we are not supposed to add it in to the values in 2005.
For every sample, the EGRET package requires a pair of numbers to define an interval in which the true value lies (ConcLow and ConcHigh). In a simple non-censored case (the reported value is above the detection limit), ConcLow equals ConcHigh and the interval collapses down to a single point.In a simple censored case, the value might be reported as \verb@<@0.2, then ConcLow=NA and ConcHigh=0.2. We use NA instead of 0 as a way to elegantly handle future logarithm calculations.
For the more complex example case, let us say dp is reported as \verb@<@0.01 and pp is reported as 0.3. We know that the total must be at least 0.3 and could be as much as 0.31. Therefore, ConcLow=0.3 and ConcHigh=0.31. Another case would be if dp is reported as \verb@<@0.005 and pp is reported \verb@<@0.2. We know in this case that the true value could be as low as zero, but could be as high as 0.205. Therefore, in this case, ConcLow=NA and ConcHigh=0.205. The Sample dataframe for the example data would be:
<<thirdExample,echo=FALSE>>=
compressedData <- compressData(DF)
Sample <- populateSampleColumns(compressedData)
The next section will talk about inputting user-generated files. getSampleDataFromFile and getSampleData assume summation with interval censoring inputs, as will be discussed in those sections.
%------------------------------------------------------------
\subsection{User-Generated Data Files}
%------------------------------------------------------------
Aside from retrieving data from the USGS web services, the dataRetrieval package also includes functions to generate the Daily and Sample data frame from local files.
%------------------------------------------------------------
\subsubsection{getDailyDataFromFile}
%------------------------------------------------------------
getDailyDataFromFile will load a user-supplied text file and convert it to the Daily dataframe. The file should have two columns, the first dates, the second values. The dates should be formatted either mm/dd/yyyy or yyyy-mm-dd. Using a 4-digit year is required. This function has the following inputs: filePath, fileName,hasHeader (TRUE/FALSE), separator, qUnit, and interactive (TRUE/FALSE). filePath is a string that defines the path to your file. This can either be a full path, or path relative to your R working directory. The input fileName is a string that defines the file name (including the extension).
Text files that contain this sort of data require some sort of a separator, for example, a 'csv' file (comma-separated value) file uses a comma to separate the date and value column. A tab delimited file would use a tab (\texttt{"}\verb@\t@\texttt{"}) rather than the comma (\texttt{"},\texttt{"}). The type of separator you use can be defined in the function call in the \texttt{"}separator\texttt{"} argument, the default is \texttt{"},\texttt{\texttt{"}}. Another function input is a logical variable: hasHeader. The default is TRUE. If your data does not have column names, set this variable to FALSE.
Finally, qUnit is a numeric argument that defines the discharge units used in the input file. The default is qUnit = 1 which assumes discharge is in cubic feet per second. If the discharge in the file is already in cubic meters per second then set qUnit = 2. If it is in some other units (like liters per second or acre-feet per day), the user will have to pre-process the data with a unit conversion that changes it to either cubic feet per second or cubic meters per second.
So, if you have a file called \texttt{"}ChoptankRiverFlow.txt\texttt{"} located in a folder called \texttt{"}RData\texttt{"} on the C drive (this is a Windows example), and the file is structured as follows (tab-separated):
\begin{verbatim}
date Qdaily
10/1/1999 107
10/3/1999 76
10/4/1999 76
10/5/1999 113
10/6/1999 98
...
\end{verbatim}
The call to open this file, convert the discharge to cubic meters per second, and populate the Daily data frame would be:
<<openDaily, eval = FALSE>>=
fileName <- "ChoptankRiverFlow.txt"
filePath <- "C:/RData/"
Daily <- getDailyDataFromFile(filePath,fileName,
separator="\t")
Microsoft Excel files can be a bit tricky to import into R directly. The simplest way to get Excel data into R is to open the Excel file in Excel, then save it as a .csv file (comma-separated values).
%------------------------------------------------------------
\subsubsection{getSampleDataFromFile}
%------------------------------------------------------------
Similarly to the previous section, getSampleDataFromFile will import a user-generated file and populate the Sample dataframe. The difference between sample data and discharge data is that the code requires a third column that contains a remark code, either blank or `\verb@<@', which will tell the program that the data was 'left-censored' (or, below the detection limit of the sensor). Therefore, the data is required to be in the form: date, remark, value. An example of a comma-delimited file would be:
\begin{verbatim}
cdate;remarkCode;Nitrate
10/7/1999,,1.4
11/4/1999,<,0.99
12/3/1999,,1.42
1/4/2000,,1.59
2/3/2000,,1.54
...
\end{verbatim}
The call to open this file, and populate the Sample dataframe would be:
<<openSample, eval = FALSE>>=
fileName <- "ChoptankRiverNitrate.csv"
filePath <- "C:/RData/"
Sample <- getSampleDataFromFile(filePath,fileName,
separator=",")
If multiple constituents are going to be summed, the format can be date, remark\_A, value\_A, remark\_b, value\_b, etc... A tab-separated example might look like this, where the columns are remark dissolved phosphate (rdp), dissolved phosphate (dp), remark particulate phosphorus (rpp), particulate phosphorus (pp), remark total phosphate (rtp), and total phosphate (tp):
\begin{verbatim}
date rdp dp rpp pp rtp tp
2003-02-15 0.020 0.500
2003-06-30 < 0.010 0.300
2004-09-15 < 0.005 < 0.200
2005-01-30 0.430
2005-05-30 < 0.050
2005-10-30 < 0.020
...
\end{verbatim}
<<openSample2, eval = FALSE>>=
fileName <- "ChoptankPhosphorus.txt"
filePath <- "C:/RData/"
Sample <- getSampleDataFromFile(filePath,fileName,
separator="\t")
@
%------------------------------------------------------------
\subsection{Merge Report}
%------------------------------------------------------------
Finally, there is a function called mergeReport that will look at both the Daily and Sample dataframe, and populate Q and LogQ columns into the Sample dataframe. The default arguments are Daily and Sample, however if you want to use other similarly structured dataframes, you can specify localDaily or localSample. Once mergeReport has been run, the Sample dataframe will be augmented with the daily discharges for all the days with samples. None of the water quality functions in EGRET will work without first having run the mergeReport function.
<<mergeExample>>=
siteNumber <- "01491000"
parameterCd <- "00631" # Nitrate
startDate <- "2000-01-01"
endDate <- "2013-01-01"
Daily <- getDVData(siteNumber, "00060", startDate, endDate)
Sample <- getSampleData(siteNumber,parameterCd, startDate, endDate)
Sample <- mergeReport()
head(Sample)
@
\FloatBarrier
%------------------------------------------------------------
\subsection{EGRET Plots}
%------------------------------------------------------------
As has been mentioned, the Daily, Sample, and INFO data frames whose construction is described in Secs. \ref{INFOsubsection} - \ref{Samplesubsection} are specifically formatted to be used with the EGRET package. The EGRET package has powerful modeling capabilities using WRTDS, but also has a variety of graphing and tabular tools to explore the data without using the WRTDS algorithm. See the EGRET vignette, user guide, and/or wiki (\url{https://github.com/USGS-R/EGRET/wiki}) for detailed information. The following figure is an example of one of the plotting functions that can be used directly from the dataRetrieval dataframes.
<<egretEx, echo=TRUE, eval=TRUE, fig.cap="Default multiPlotDataOverview">>=
# Continuing Choptank example from the previous sections
library(EGRET)
multiPlotDataOverview()
@
%------------------------------------------------------------
\section{Summary}
%------------------------------------------------------------
Tables \ref{tab:dataRetrievalFunctions1} and \ref{tab:dataRetrievalMisc} summarize the data retrieval functions:
\begin{table}
\centering
\begin{threeparttable}[b]
\caption{dataRetrieval functions}
\label{tab:dataRetrievalFunctions1}
\begin{tabular}{lll}
\hline
Data Type & Function Name & Description \\
\hline
Daily & retrieveNWISData & Raw USGS daily data \\
Daily\tnote{1} & getDVData & USGS daily values \\
Daily\tnote{1} & getDailyDataFromFile & User generated daily data \\
Sample & retrieveNWISqwData & Raw USGS water quality data \\
Sample & getRawQWData & Raw Water Quality Data Portal data \\
Sample & getQWDataFromFile & Raw user generated water quality data \\
Sample & getQWData & USGS Water Quality Portal data \\
Sample & getWQPData & General Water Quality Portal\\
Sample\tnote{1} & getSampleData & USGS water quality data\\
Sample\tnote{1} & getSTORETSampleData & STORET Water Quality Data Portal data \\
Sample\tnote{1} & getSampleDataFromFile & User generated sample data \\
Unit & retrieveUnitNWISData & Raw USGS instantaneous data \\
Information\tnote{1} & getMetaData & USGS station and parameter code information \\
Information & getParameterInfo & USGS parameter code information \\
Information & getSiteFileData & USGS station information \\
Information & getDataAvailability & Data available at USGS stations \\
\hline
\end{tabular}
\begin{tablenotes}
\item[1] Indicates that the function creates a data frame suitable for use in EGRET software
\end{tablenotes}
\end{threeparttable}
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
% \begin{table}[!ht]
% \begin{minipage}{\linewidth}
% \begin{center}
% \caption{dataRetrieval functions}
% \begin{tabular}{lll}
% \hline
% Data Type & Function Name & Description \\
% \hline
% Daily & retrieveNWISData & Raw USGS daily data \\
% Daily\footnotemark[1] & getDVData & USGS daily values \\
% Daily\footnotemark[1] & getDailyDataFromFile & User generated daily data \\
% Sample & retrieveNWISqwData & Raw USGS water quality data \\
% Sample & getRawQWData & Raw Water Quality Data Portal data \\
% Sample & getQWDataFromFile & Raw user generated water quality data \\
% Sample & getQWData & USGS Water Quality Portal data \\
% Sample & getWQPData & General Water Quality Portal\\
% Sample\footnotemark[1] & getSampleData & USGS water quality data\\
% Sample\footnotemark[1] & getSTORETSampleData & STORET Water Quality Data Portal data \\
% Sample\footnotemark[1] & getSampleDataFromFile & User generated sample data \\
% Unit & retrieveUnitNWISData & Raw USGS instantaneous data \\
% Information\footnotemark[1] & getMetaData & USGS station and parameter code information \\
% Information & getParameterInfo & USGS parameter code information \\
% Information & getSiteFileData & USGS station information \\
% Information & getDataAvailability & Data available at USGS stations \\
% \hline
% \end{tabular}
% \end{center}
% \end{minipage}
% \end{table}
%
% \footnotetext[1]{Indicates that function creates a data frame suitable for use in EGRET software}
\begin{table}[!ht]
\begin{minipage}{\linewidth}
\begin{center}
\caption{dataRetrieval miscellaneous functions}
\begin{tabular}{ll}
\hline
Function Name & Description \\
\hline
compressData & Converts value/qualifier into ConcLow, ConcHigh, Uncen\\
getRDB1Data & Retrieves and converts RDB data to dataframe\\
getWaterML1Data & Retrieves and converts WaterML1 data to dataframe\\
getWaterML2Data & Retrieves and converts WaterML2 data to dataframe\\
mergeReport & Merges flow data from the daily record into the sample record\\
populateDateColumns & Generates Julian, Month, Day, DecYear, and MonthSeq columns\\
removeDuplicates & Removes duplicated rows\\
renameColumns & Renames columns from raw data retrievals\\
\hline
\end{tabular}
\end{center}
\end{minipage}
\end{table}
%------------------------------------------------------------
\section{Getting Started in R}
\label{sec:appendix1}
%------------------------------------------------------------
This section describes the options for downloading and installing the dataRetrieval package.
%------------------------------------------------------------
\subsection{New to R?}
%------------------------------------------------------------
If you are new to R, you will need to first install the latest version of R, which can be found here: \url{http://www.r-project.org/}.
There are many options for running and editing R code, one nice environment to learn R is RStudio. RStudio can be downloaded here: \url{http://rstudio.org/}. Once R and RStudio are installed, the dataRetrieval package needs to be installed as described in the next section.
At any time, you can get information about any function in R by typing a question mark before the functions name. This will open a file (in RStudio, in the Help window) that describes the function, the required arguments, and provides working examples.
<<helpFunc,eval = FALSE>>=
?removeDuplicates
@
This will open a help file similar to Figure \ref{fig:help}.
\FloatBarrier
To see the raw code for a particular code, type the name of the function, without parentheses.:
<<rawFunc,eval = TRUE>>=
removeDuplicates
@
\begin{figure}[ht!]
\centering
\resizebox{0.95\textwidth}{!}{\includegraphics{Rhelp.png}}
\caption{A simple R help file}
\label{fig:help}
\end{figure}
Additionally, many R packages have vignette files attached (such as this paper). To view the vignette:
<<seeVignette,eval = FALSE>>=
vignette(dataRetrieval)
@
\FloatBarrier
\clearpage
%------------------------------------------------------------
\subsection{R User: Installing dataRetrieval}
%------------------------------------------------------------
Before installing dataRetrieval, a number of packages upon which dataRetrieval depends need to be installed must be installed from CRAN:
<<installFromCran,eval = FALSE>>=
install.packages(c("zoo","XML","RCurl","plyr"))
install.packages("dataRetrieval", repos="http://usgs-r.github.com")
It is a good idea to re-start R after installing the package, especially if installing an updated version. Some users have found it necessary to delete the previous version's package folder before installing newer version of dataRetrieval. If you are experiencing issues after updating a package, trying deleting the package folder - the default location for Windows is something like:
C:/Users/userA/Documents/R/win-library/2.15/dataRetrieval
The default for a Mac is something like:
/Users/userA/Library/R/2.15/library/dataRetrieval
Then, re-install the package using the directions above. Moving to CRAN should solve this problem.
After installing the package, you need to open the library each time you re-start R. This is done with the simple command:
<<openLibraryTest, eval=FALSE>>=
library(dataRetrieval)
@
%------------------------------------------------------------
\section{Creating tables in Microsoft from R}
\label{app:createWordTable}
%------------------------------------------------------------
There are a few steps that are required in order to create a table in a Microsoft product (Excel, Word, Powerpoint, etc.) from an R dataframe. There are certainly a variety of good methods, one of which is detailed here. The example we will step through here will be to create a table in Microsoft Excel based on the dataframe tableData:
<<label=getSiteApp, echo=TRUE>>=
availableData <- getDataAvailability(siteNumber)
dailyData <- availableData["dv" == availableData$service,]
dailyData <- dailyData["00003" == dailyData$statCd,]
shortName=srsname,
Start=startDate,
End=endDate,
Count=count,
Units=parameter_units)
@
First, save the dataframe as a tab delimited file (you don't want to use comma delimited because there are commas in some of the data elements):
<<label=saveData, echo=TRUE, eval=FALSE>>=
write.table(tableData, file="tableData.tsv",sep="\t",
row.names = FALSE,quote=FALSE)
@
This will save a file in your working directory called tableData.tsv. You can see your working directory by typing getwd() in the R console. Opening the file in a general-purpose text editor, you should see the following:
\begin{verbatim}
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
Temperature, water 2010-10-01 2012-06-24 575 deg C
Stream flow, mean. daily 1948-01-01 2013-03-13 23814 cfs
Specific conductance 2010-10-01 2012-06-24 551 uS/cm @25C
Suspended sediment concentration (SSC) 1980-10-01 1991-09-30 3651 mg/l
Suspended sediment discharge 1980-10-01 1991-09-30 3652 tons/day
\end{verbatim}
To open this file in Excel:
\begin{enumerate}
\item Open Excel
\item Click on the File tab
\item Click on the Open option
\item Browse to the working directory (as shown in the results of getwd())
\item Next to the File name text box, change the dropdown type to All Files (*.*)
\item Double click tableData.tsv
\item A text import wizard will open up, in the first window, choose the Delimited radio button if it is not automatically picked, then click on Next.
\item In the second window, click on the Tab delimiter if it is not automatically checked, then click Finished.
\item Use the many formatting tools within Excel to customize the table
\end{enumerate}
From Excel, it is simple to copy and paste the tables in other Microsoft products. An example using one of the default Excel table formats is here.
\begin{figure}[ht!]
\centering
\resizebox{0.9\textwidth}{!}{\includegraphics{table1.png}}
\caption{A simple table produced in Microsoft Excel}
\label{overflow}
\end{figure}
\clearpage
%------------------------------------------------------------
% BIBLIO
%------------------------------------------------------------
\begin{thebibliography}{10}
\bibitem{HirschI}
Helsel, D.R. and R. M. Hirsch, 2002. Statistical Methods in Water Resources Techniques of Water Resources Investigations, Book 4, chapter A3. U.S. Geological Survey. 522 pages. \url{http://pubs.usgs.gov/twri/twri4a3/}
\bibitem{HirschII}
Hirsch, R. M., Moyer, D. L. and Archfield, S. A. (2010), Weighted Regressions on Time, Discharge, and Season (WRTDS), with an Application to Chesapeake Bay River Inputs. JAWRA Journal of the American Water Resources Association, 46: 857-880. doi: 10.1111/j.1752-1688.2010.00482.x \url{http://onlinelibrary.wiley.com/doi/10.1111/j.1752-1688.2010.00482.x/full}
\bibitem{HirschIII}
Sprague, L. A., Hirsch, R. M., and Aulenbach, B. T. (2011), Nitrate in the Mississippi River and Its Tributaries, 1980 to 2008: Are We Making Progress? Environmental Science \& Technology, 45 (17): 7209-7216. doi: 10.1021/es201221s \url{http://pubs.acs.org/doi/abs/10.1021/es201221s}
\end{thebibliography}
\end{document}
\end{document}