/
read_formwqp.R
198 lines (179 loc) · 6.54 KB
/
read_formwqp.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#' Format data and station metadata from the Water Quality Portal
#'
#' @param res A data frame containing results obtained from the API
#' @param sta A data frame containing station metadata obtained from the API
#' @param org chr string indicating the organization identifier
#' @param type chr string indicating data type to download, one of \code{"wq"} or \code{"fib"}
#' @param trace Logical indicating whether to display progress messages, default is \code{FALSE}
#'
#' @return A data frame containing formatted water quality and station metadata
#'
#' @details This function is used by \code{\link{read_importwqp}} to combine, format, and process data (\code{res}) and station metadata (\code{sta}) obtained from the Water Quality Portal for the selected county and data type. The resulting data frame includes the date, time, station identifier, latitude, longitude, variable name, value, unit, and quality flag.
#'
#' @concept read
#'
#' @importFrom dplyr %>%
#'
#' @seealso \code{\link{read_importwqp}}
#'
#' @export
#'
#' @examples
#' \dontrun{
#' url <- list(
#' Result = "https://www.waterqualitydata.us/data/Result/search?mimeType=csv&zip=no",
#' Station = "https://www.waterqualitydata.us/data/Station/search?mimeType=csv&zip=no"
#' )
#'
#' headers <- c(
#' "Content-Type" = "application/json",
#' "Accept" = "application/zip"
#' )
#'
#' body <- list(
#' organization = c("21FLMANA_WQX"),
#' sampleMedia = c("Water"),
#' characteristicType = c("Information", "Nutrient", "Biological, Algae, Phytoplankton,
#' Photosynthetic Pigments"),
#' providers = c("STORET"),
#' siteType = c("Estuary")
#' )
#'
#' res <- url[['Result']] %>%
#' httr::POST(httr::add_headers(headers), body = jsonlite::toJSON(body)) %>%
#' httr::content('text') %>%
#' read.csv(text = .)
#'
#' sta <- url[['Station']] %>%
#' httr::POST(httr::add_headers(headers), body = jsonlite::toJSON(body)) %>%
#' httr::content('text') %>%
#' read.csv(text = .)
#'
#' # combine and format
#' read_formwqp(res, sta, '21FLMANA_WQX', type = 'wq')
#'}
read_formwqp <- function(res, sta, org, type, trace = F){
# get type
type <- match.arg(type, c('fib', 'wq'))
# get station column name based on county input
stanm <- util_orgin(org, stanm = T)
# entries for missing horizontal datums
misdatum <- c('OTHER', 'UNKWN')
if(trace)
cat('Combining and formatting output...\n')
# format station metadata
stafrm <- sta %>%
dplyr::select(ident = MonitoringLocationIdentifier,
lat = LatitudeMeasure, lon = LongitudeMeasure,
datum = HorizontalCoordinateReferenceSystemDatumName,
class = MonitoringLocationTypeName
) %>%
dplyr::mutate(
epsg = case_when(
datum == 'WGS84' ~ 4326,
datum == 'NAD83' ~ 4269,
datum == 'NAD27' ~ 4267,
datum %in% misdatum ~ 4326
),
class = case_when(
class != 'Estuary' ~ 'Fresh',
T ~ 'Estuary'
)
)
# warning for missing datum
if(any(stafrm$datum %in% misdatum))
warning('Missing datum information present for some stations, converted to EPSG 4326')
# get relevant results columns, combine with stafrm
resfrm <- res %>%
dplyr::select(date = ActivityStartDate, type = ActivityTypeCode, time = ActivityStartTime.Time,
ident = MonitoringLocationIdentifier, var = CharacteristicName, val = ResultMeasureValue,
uni = ResultMeasure.MeasureUnitCode,
Sample_Depth_m = ActivityDepthHeightMeasure.MeasureValue,
depth_uni = ActivityDepthHeightMeasure.MeasureUnitCode
) %>%
dplyr::left_join(stafrm, by = 'ident') %>%
dplyr::filter(type %in% c('Field Msr/Obs', 'Sample-Routine')) %>%
dplyr::filter(!val %in% c('*Not Reported', 'Not Reported')) %>%
dplyr::mutate(
time = ifelse(time == '', '00:00:00', time),
Sample_Depth_m = case_when(
depth_uni == 'ft' ~ Sample_Depth_m / 3.281,
T ~ Sample_Depth_m
)
) %>%
unite('SampleTime', date, time, sep = ' ') %>%
dplyr::mutate(
station = gsub(paste0('^', org, '\\-'), '', ident),
SampleTime = lubridate::ymd_hms(SampleTime, tz = 'America/Jamaica'),
yr = lubridate::year(SampleTime),
mo = lubridate::month(SampleTime),
qual = ifelse(val %in% c('*Non-detect', '*Present <QL'), 'U', NA_character_),
qual = ifelse(val %in% '*Present >QL', 'I', NA_character_),
val = ifelse(val %in% c('*Non-detect', '*Present <QL', '*Present >QL'), '', val)
)
# format and combine data if wq
if(type == 'wq'){
# combine and process
out <- resfrm %>%
dplyr::filter(!var %in% c('Nitrate', 'Depth')) %>% # only kept no23
dplyr::filter(!uni %in% 'ft') %>%
dplyr::mutate(
var = dplyr::case_when(
grepl('Nitri|Nitra', var) ~ 'no23',
grepl('Ammonia', var) ~ 'nh34',
grepl('^Chlorophyll a, corrected', var) ~ 'chla_corr',
grepl('^Chlorophyll a, free', var) ~ 'chla_uncorr',
grepl('Secchi', var) ~ 'secchi',
grepl('Kjeldahl', var) ~ 'tkn',
grepl('Phosphorus', var) ~ 'tp',
grepl('Orthophosphate', var) ~ 'orthop',
grepl('Salinity', var) ~ 'sal',
grepl('Temperature, water', var) ~ 'temp',
grepl('Turbidity', var) ~ 'turb'
),
uni = case_when(
uni == 'mg/m3' ~ 'ugl',
uni == 'mg/L' ~ 'mgl',
uni == 'ppt' ~ 'ppth',
T ~ uni
)
)
}
# format and combine data if wq
if(type == 'fib'){
# combine and process
out <- resfrm %>%
dplyr::filter(!is.na(uni)) %>%
dplyr::mutate(
var = dplyr::case_when(
grepl('^Escherichia', var) ~ 'ecoli',
grepl('^Fecal', var) ~ 'fcolif',
grepl('^Entero', var) ~ 'ecocci',
grepl('^Total', var) ~ 'totcol'
)
)
}
# final formatting
out <- out %>%
dplyr::filter(!is.na(var)) %>%
dplyr::filter(!is.na(val)) %>%
dplyr::mutate(
val = as.numeric(val)
) %>%
tidyr::nest(.by = datum) %>%
dplyr::mutate(
data = purrr::map(data, function(x){
sf::st_as_sf(x, coords = c('lon', 'lat'), crs = unique(x$epsg), remove = F) %>%
sf::st_transform(crs = 4326)
})
) %>%
tidyr::unnest('data') %>%
sf::st_as_sf() %>%
sf::st_set_geometry(NULL) %>%
select(station, SampleTime, class, yr, mo, Latitude = lat, Longitude = lon,
Sample_Depth_m, var, val, uni, qual) %>%
unique()
# rename station column based on org
names(out)[names(out) %in% 'station'] <- stanm
return(out)
}