From 76c8b01f43671e7b5581933b94846862df8bbfea Mon Sep 17 00:00:00 2001 From: Erik Leppo Date: Tue, 15 Oct 2024 12:38:11 -0400 Subject: [PATCH] v1.2.0.9002 - fix: Replace `rgdal` functions with ones from `sf` package, Issue \#44 - refactor: Remove XLConnect, Issue \#48 - DESCRIPTION, Suggests - MBSStools_vignette - fixe: Vignette now builds, Issue \#33 --- DESCRIPTION | 10 +- NEWS | 10 +- NEWS.md | 10 +- NEWS.rmd | 9 + R/MapTaxaObs.R | 57 +- doc/MBSStools_vignette.R | 327 --- doc/MBSStools_vignette.html | 2622 ----------------------- inst/extdata/Notebook_MBSStools.Rmd | 6 +- inst/extdata/Notebook_MBSStools.nb.html | 1806 ++++++++++++++-- inst/shiny-examples/MBSStools/ui.R | 2 +- man/MapTaxaObs.Rd | 7 +- vignettes/MBSStools_vignette.Rmd | 133 +- 12 files changed, 1845 insertions(+), 3154 deletions(-) delete mode 100644 doc/MBSStools_vignette.R delete mode 100644 doc/MBSStools_vignette.html diff --git a/DESCRIPTION b/DESCRIPTION index c4b4e0f..ce6eb3a 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -4,7 +4,7 @@ Description: Suite of tools for data manipulation and calculations for Maryland DNR MBSS program. Includes functions for calculating FIBI, BIBI (MBSS genus), BIBI (MSW family), PHI, flow sums, ion contributions, and taxa distribution maps. -Version: 1.2.0.9001 +Version: 1.2.0.9002 Authors@R: c( person("Erik W.", "Leppo", email="Erik.Leppo@tetratech.com", role=c("aut","cre")), person("Ann","Roseberry Lincoln", role="ctb"), @@ -14,10 +14,9 @@ Depends: R (>= 3.4.0) License: GPL (>= 3) Encoding: UTF-8 URL: https://github.com/leppott/MBSStools -RoxygenNote: 7.3.1 +RoxygenNote: 7.3.2 Imports: - dplyr, - rgdal + dplyr Suggests: DT, ggplot2, @@ -30,8 +29,7 @@ Suggests: shiny, shinyjs, sp, - testthat, - XLConnect + testthat VignetteBuilder: knitr LazyData: true BugReports: https://github.com/leppott/MBSStools/issues diff --git a/NEWS b/NEWS index 0a30175..b0ec9b7 100644 --- a/NEWS +++ b/NEWS @@ -3,7 +3,15 @@ NEWS-MBSStools - #> Last Update: 2024-04-08 12:38:08.080495 + #> Last Update: 2024-10-15 12:37:10.670714 + +# MBSStools v1.2.0.9002 (2024-04-08) + +- fix: Replace `rgdal` functions with ones from `sf` package, Issue \#44 +- refactor: Remove XLConnect, Issue \#48 + - DESCRIPTION, Suggests + - MBSStools_vignette +- fixe: Vignette now builds, Issue \#33 # MBSStools v1.2.0.9001 (2024-04-08) diff --git a/NEWS.md b/NEWS.md index 0a30175..b0ec9b7 100644 --- a/NEWS.md +++ b/NEWS.md @@ -3,7 +3,15 @@ NEWS-MBSStools - #> Last Update: 2024-04-08 12:38:08.080495 + #> Last Update: 2024-10-15 12:37:10.670714 + +# MBSStools v1.2.0.9002 (2024-04-08) + +- fix: Replace `rgdal` functions with ones from `sf` package, Issue \#44 +- refactor: Remove XLConnect, Issue \#48 + - DESCRIPTION, Suggests + - MBSStools_vignette +- fixe: Vignette now builds, Issue \#33 # MBSStools v1.2.0.9001 (2024-04-08) diff --git a/NEWS.rmd b/NEWS.rmd index 70c4bff..23f157e 100644 --- a/NEWS.rmd +++ b/NEWS.rmd @@ -17,6 +17,15 @@ knitr::opts_chunk$set( cat(paste0("Last Update: ",Sys.time())) ``` +MBSStools v1.2.0.9002 (2024-04-08) +================ + +* fix: Replace `rgdal` functions with ones from `sf` package, Issue #44 +* refactor: Remove XLConnect, Issue #48 + + DESCRIPTION, Suggests + + MBSStools_vignette +* fixe: Vignette now builds, Issue #33 + MBSStools v1.2.0.9001 (2024-04-08) ================ * fix: Update examples and vignette to not use droplevels() diff --git a/R/MapTaxaObs.R b/R/MapTaxaObs.R index 135da61..7ce7af5 100644 --- a/R/MapTaxaObs.R +++ b/R/MapTaxaObs.R @@ -14,7 +14,9 @@ #' Tests for existence of Data, GIS directories and required files. On failure, #' stops and prints missing directories/files to screen. #' -#' The R libraries rgdal, sf, and readxl are required for this function. +#' The R libraries `rgdal`, `sf`, and `readxl` are required for this function. +#' The `rgdal` package was deprecated in 2023. In 2024 revised this fucntion to +#' use functions from the `sf` package. #' #' @param obs Excel file containing 3 columns: TaxaName, Latitude83, Longitude83 #' @param xWalk Crosswalk (Excel file) of taxa names between taxa name in @@ -71,6 +73,9 @@ #' #' # Create maps #' MapTaxaObs(obs, xWalk, dirMain) +#' +#' # Open folder (Windows only) +#' # shell.exec(tempdir()) # #' @export MapTaxaObs <- function(obs @@ -123,8 +128,6 @@ MapTaxaObs <- function(obs # shell.exec(dirMain) }## IF ~ boo_QC ~ END - - # 2021-01-10 # Define missing variables # bindings for global variables ----- @@ -273,15 +276,6 @@ MapTaxaObs <- function(obs ppi <- 72 #dsn<-paste(dirMain,dirGIS,sep="/") dsn <- file.path(dirMain, dirGIS) - # state <- rgdal::readOGR(dsn = dsn - # , layer = "MD_State_Boundary" - # , verbose=verbose) - # coastline <- rgdal::readOGR(dsn = dsn - # , layer = "MD_Coast_Hydrology" - # , verbose=verbose) - # counties <- rgdal::readOGR(dsn = dsn - # , layer = "MD_Boundary_County_Detailed" - # , verbose=verbose) # sf version state <- sf::st_read(dsn = dsn @@ -307,30 +301,39 @@ MapTaxaObs <- function(obs , pointsize = 12 , bg = "white") plot(sf::st_geometry(state) - , col="white" + , col = "white" , border = "gray") plot(sf::st_geometry(coastline) , add = TRUE , col = "light blue" - , border=FALSE) + , border = FALSE) plot(sf::st_geometry(counties) , add = TRUE , col = "white" , border = "darkslategray" , lwd = 0.5) - #xy <- df.taxon.sites[,2:3] - proj.sites <- rgdal::project(cbind(df.taxon.sites$Longitude83 - , df.taxon.sites$Latitude83) - , - "+proj=lcc +lat_1=39.45 +lat_2=38.3 +lat_0=37.66666666666666 +lon_0=-77 - +x_0=400000 +y_0=0 +datum=NAD83 +units=m +no_defs") - graphics::points(proj.sites[, 1] - , proj.sites[, 2] - , pch = 21 - , col = "black" - , bg = "green" - , cex = 1.0) + + ### sites + # 4326, WGS 84 + # 6487, NAD83(2011)/Maryland in meters + # 6488, NAD83(2011)/Maryland in US survey feet + # 26985, NAD83/Maryland *this one* + # 2248 + sites_wgs84 <- sf::st_as_sf(df.taxon.sites, + coords = c("Longitude83", "Latitude83"), + crs = 4326) + sites_nad83md_m <- sf::st_transform(sites_wgs84, crs = 26985) + #### plot + plot(sites_nad83md_m, + pch = 21, + col = "black", + bg = "green", + cex = 1.0, + type = "p", + add = TRUE) + grDevices::dev.off() + # user feedback if (verbose == TRUE) {##IF.verbose.START message(paste0("Saving map " @@ -344,7 +347,7 @@ MapTaxaObs <- function(obs }##IF.verbose.END ##PLOT.END }##FOR.i.END - # + # 6. Clean up #### # Number on Non-Matches n.nomatch <- nrow(df.taxa.nomatch) diff --git a/doc/MBSStools_vignette.R b/doc/MBSStools_vignette.R deleted file mode 100644 index eaf407e..0000000 --- a/doc/MBSStools_vignette.R +++ /dev/null @@ -1,327 +0,0 @@ -## ----install, eval=FALSE------------------------------------------------------ -# install.packages("devtools") -# library(devtools) -# install_github("leppott/MBSStools") - -## ----install example 2, eval=FALSE-------------------------------------------- -# install.package("dplyr") - -## ----IBI Fish, echo=TRUE------------------------------------------------------ -# Metrics, Fish -library(MBSStools) -#(generate values then score)s -myIndex <- "MBSS.2005.Fish" -# Thresholds -thresh <- metrics_scoring -# get metric names for myIndex -(myMetrics.Fish <- as.character(unique(thresh[thresh[,"Index.Name"] == myIndex,"MetricName.Other"]))) -# Taxa Data -myDF.Fish <- taxa_fish -myMetric.Values.Fish <- metric.values(myDF.Fish, "fish", myMetrics.Fish, TRUE) -#View(myMetric.Values.Fish) -# SCORE -Metrics.Fish.Scores <- metric.scores(myMetric.Values.Fish, myMetrics.Fish, "Index.Name", "FIBISTRATA", thresh) -# View Results -knitr::kable(head(Metrics.Fish.Scores)) - -## ----IBI Ben MBSS, echo=TRUE-------------------------------------------------- -# Metrics, Index, Benthic Macroinvertebrates, genus -# (generate values then scores) -myIndex <- "MBSS.2005.Bugs" -# Thresholds -thresh <- metrics_scoring -# get metric names for myIndex -(myMetrics.Bugs.MBSS <- as.character(unique(thresh[thresh[,"Index.Name"] == myIndex,"MetricName.Other"]))) -# Taxa Data -myDF.Bugs.MBSS <- taxa_bugs_genus -myMetric.Values.Bugs.MBSS <- metric.values(myDF.Bugs.MBSS, "bugs", myMetrics.Bugs.MBSS) -#View(myMetric.Values.Bugs.MBSS) -# SCORE -Metrics.Bugs.Scores.MBSS <- metric.scores(myMetric.Values.Bugs.MBSS, myMetrics.Bugs.MBSS, "INDEX.NAME", "STRATA_R", thresh) -# View Results -#View(Metrics.Bugs.Scores.MBSS) - -# QC bug count -Metrics.Bugs.Scores.MBSS[Metrics.Bugs.Scores.MBSS[,"totind"]>120,"QC_Count"] <- "LARGE" -Metrics.Bugs.Scores.MBSS[Metrics.Bugs.Scores.MBSS[,"totind"]<60,"QC_Count"] <- "SMALL" -Metrics.Bugs.Scores.MBSS[is.na(Metrics.Bugs.Scores.MBSS[,"QC_Count"]),"QC_Count"] <- "OK" -# table of QC_Count -knitr::kable(head(Metrics.Bugs.Scores.MBSS)) - -## ----IBI Ben MSW, echo=TRUE--------------------------------------------------- -# Metrics, MSW Index, Benthic Macroinvertebrates, family -myIndex <- "MSW.1999.Bugs" -# Thresholds -thresh <- metrics_scoring -# get metric names for myIndex -(myMetrics.Bugs.MSW <- as.character(unique(thresh[thresh[,"Index.Name"] == myIndex,"MetricName.Other"]))) -# Taxa Data -myDF.Bugs.MSW <- taxa_bugs_family -myMetric.Values.Bugs.MSW <- metric.values(myDF.Bugs.MSW, "bugs", myMetrics.Bugs.MSW) -#View(myMetric.Values.Bugs.MSW) -# SCORE -Metrics.Bugs.Scores.MSW <- metric.scores(myMetric.Values.Bugs.MSW, myMetrics.Bugs.MSW, "INDEX.NAME", "STRATA_R", thresh) -# View Results -knitr::kable(head(Metrics.Bugs.Scores.MSW)) - -## ----TaxaMaps, eval=FALSE----------------------------------------------------- -# # Set Working Directory -# wd <- getwd() -# # Create Example Data if Needed -# ## Create Directories -# myDir.create <- file.path(wd,"Data") -# ifelse(dir.exists(myDir.create)==FALSE,dir.create(myDir.create),"Directory already exists") -# myDir.create <- file.path(wd,"GIS") -# ifelse(dir.exists(myDir.create)==FALSE,dir.create(myDir.create),"Directory already exists") -# myDir.create <- file.path(wd,"Maps") -# ifelse(dir.exists(myDir.create)==FALSE,dir.create(myDir.create),"Directory already exists") -# ## Create Data -# ### Taxa Data -# myFiles <- c("AllFish_95to16.xls", "TaxaMapsCrossWalk20170731.xlsx") -# file.copy(file.path(path.package("MBSStools"),"extdata",myFiles),file.path(wd,"Data",myFiles)) -# ### GIS -# unzip(file.path(path.package("MBSStools"),"extdata","MD_GIS.zip"),exdir=file.path(wd,"GIS")) - -## ----TaxaMaps Input, echo=FALSE----------------------------------------------- -# library -library(readxl) - -# data files -obs <- "AllFish_95to16.xls" -xWalk <- "TaxaMapsCrossWalk20170731.xlsx" - -all.taxa <- system.file("extdata", obs, package = "MBSStools") -taxa.lu <- system.file("extdata", xWalk, package = "MBSStools") - -# Read in Taxon observations -df.taxa.obs <- readxl::read_excel(all.taxa, sheet=1,col_names=TRUE,skip=0) -df.taxa.obs <- as.data.frame(df.taxa.obs) -df.taxa.obs[,1] <- tolower(df.taxa.obs[,1]) -#df.taxa.obs <- as.data.frame(cbind(tolower(df.taxa.obs[,"TaxaName"]), df.taxa.obs[,2:3])) -colnames(df.taxa.obs)[1] <- "CommonName" - -head(df.taxa.obs) - -## ----TaxaMaps Crosswalk, echo=FALSE------------------------------------------- -# library -library(readxl) - -# data files -obs <- "AllFish_95to16.xls" -xWalk <- "TaxaMapsCrossWalk20170731.xlsx" - -all.taxa <- system.file("extdata", obs, package = "MBSStools") -taxa.lu <- system.file("extdata", xWalk, package = "MBSStools") - -# Read in TaxaMapsCrossWalk.xlsx -df.lu.taxa <- readxl::read_excel(taxa.lu,sheet=1,col_names=TRUE,skip=0) -df.lu.taxa <- as.data.frame(df.lu.taxa[,c("CommonName","MapName")]) -df.lu.taxa[,"CommonName"] <- tolower(df.lu.taxa[,"CommonName"]) -# df.lu.taxa <- as.data.frame(cbind(tolower(df.lu.taxa[,"CommonName"]),df.lu.taxa[,"MapName"])) -# colnames(df.lu.taxa)[1:2] <- c("CommonName","MapName") - -head(df.lu.taxa) - - -## ----TaxaMaps Example Code, eval=FALSE---------------------------------------- -# # Set Working Directory -# wd <- getwd() -# -# # Inputs -# Obs <- "AllFish_95to16.xls" -# XWalk <- "TaxaMapsCrossWalk20170731.xlsx" -# wd <- getwd() -# -# # Create maps -# MapTaxaObs(Obs, XWalk, wd, onlymatches = FALSE) - -## ----TaxaMap Brown Trout, echo=FALSE, results="hide", fig.show='hold', warnings=FALSE, eval=TRUE---- -# example map. -# include only brown trout -# brntrout.png -# assume already created directories - -## library -library(readxl) -library(rgdal) - -# Set Working Directory -wd <- getwd() -# Create Example Data if Needed -## Create Directories -myDir.create <- file.path(wd,"Data") -ifelse(dir.exists(myDir.create)==FALSE,dir.create(myDir.create),"Directory already exists") -myDir.create <- file.path(wd,"GIS") -ifelse(dir.exists(myDir.create)==FALSE,dir.create(myDir.create),"Directory already exists") -myDir.create <- file.path(wd,"Maps") -ifelse(dir.exists(myDir.create)==FALSE,dir.create(myDir.create),"Directory already exists") -## Create Data -### Taxa Data -myFiles <- c("AllFish_95to16.xls", "TaxaMapsCrossWalk20170731.xlsx") -file.copy(file.path(path.package("MBSStools"),"extdata",myFiles),file.path(wd,"Data",myFiles)) -### GIS -unzip(file.path(path.package("MBSStools"),"extdata","MD_GIS.zip"),exdir=file.path(wd,"GIS")) - - - -# data files -obs <- "AllFish_95to16.xls" -xWalk <- "TaxaMapsCrossWalk20170731.xlsx" - -oldwd <- getwd() -setwd("..") #resets to vignette dir when run as code chunk -dirMain <- getwd() -dirData = "Data" -dirGIS = "GIS" -verbose = TRUE -onlymatches = TRUE - -all.taxa <- system.file("extdata", obs, package = "MBSStools") -taxa.lu <- system.file("extdata", xWalk, package = "MBSStools") - -# Read in Taxon observations -df.taxa.obs <- readxl::read_excel(all.taxa,sheet=1,col_names=TRUE,skip=0) -df.taxa.obs <- as.data.frame(df.taxa.obs) -df.taxa.obs[,1] <- tolower(df.taxa.obs[,1]) -#df.taxa.obs <- as.data.frame(cbind(tolower(df.taxa.obs[,"TaxaName"]), df.taxa.obs[,2:3])) -colnames(df.taxa.obs)[1] <- "CommonName" - -## Trim to browntrout -df.taxa.obs <- df.taxa.obs[df.taxa.obs[,"CommonName"]=="brown trout",] - - -# Read in TaxaMapsCrossWalk.xlsx -df.lu.taxa <- readxl::read_excel(taxa.lu,sheet=1,col_names=TRUE,skip=0) -df.lu.taxa <- as.data.frame(df.lu.taxa[,c("CommonName","MapName")]) -df.lu.taxa[,"CommonName"] <- tolower(df.lu.taxa[,"CommonName"]) -# df.lu.taxa <- as.data.frame(cbind(tolower(df.lu.taxa[,"CommonName"]),df.lu.taxa[,"MapName"])) -# colnames(df.lu.taxa)[1:2] <- c("CommonName","MapName") - - # 4. Munge Data #### -# Compare TaxaName to CommonName -taxa.names <- as.vector(df.lu.taxa[,"CommonName"]) -matches <- as.vector(df.taxa.obs[,"CommonName"]) %in% taxa.names -df.taxa.nomatch <- as.data.frame(unique(sort(df.taxa.obs[,"CommonName"][!matches]))) -colnames(df.taxa.nomatch)[1] <- "CommonName" -df.taxa.match <- as.data.frame(unique(sort(df.taxa.obs[,"CommonName"][matches]))) -colnames(df.taxa.match)[1] <- "CommonName" - -#if (onlymatches == TRUE) { - # Create a data frame of common names and filenames for matching taxa - map.taxa <- subset(df.lu.taxa, CommonName %in% df.taxa.match[,"CommonName"], - select = c(CommonName,MapName)) - -# 5. Mapping #### -ppi <- 72 -#dsn<-paste(dirMain,dirGIS,sep="/") -dsn <- file.path(dirMain, dirGIS) -state <- rgdal::readOGR(dsn = dsn, layer = "MD_State_Boundary", verbose=verbose) -coastline <- rgdal::readOGR(dsn = dsn, layer = "MD_Coast_Hydrology", verbose=verbose) -counties <- rgdal::readOGR(dsn = dsn, layer = "MD_Boundary_County_Detailed", verbose=verbose) - -i<-1 - -taxon <- as.character(map.taxa$CommonName[i]) - - - filename <- map.taxa$MapName[i] - df.taxon.sites <- subset(df.taxa.obs, df.taxa.obs[,"CommonName"]==taxon) - df.taxon.sites <- subset(df.taxon.sites, !is.na(df.taxon.sites["Latitude83"])) - - - plot(state, col="white", border="gray") - plot(coastline, add = TRUE, col="light blue", border=FALSE) - plot(counties, add = TRUE, col="white", border="darkslategray", lwd=0.5) - #xy <- df.taxon.sites[,2:3] - proj.sites <- rgdal::project(cbind(df.taxon.sites$Longitude83,df.taxon.sites$Latitude83), - "+proj=lcc +lat_1=39.45 +lat_2=38.3 +lat_0=37.66666666666666 +lon_0=-77 - +x_0=400000 +y_0=0 +datum=NAD83 +units=m +no_defs") - points(proj.sites[,1], proj.sites[,2], pch=21, col="black", bg="green", cex=1.0) - - - #reset old working directory - #setwd <- oldwd - -## ----Discharge, eval=FALSE---------------------------------------------------- -# library(MBSStools) -# # data -# MBSS.flow <- MBSS.flow -# # calculate flow -# flow.cell <- FlowSum(MBSS.flow, returnType="cell") -# flow.sample <- FlowSum(MBSS.flow) -# # examine data -# View(flow.cell) -# View(flow.sample) -# # Example Save file (tab delimited text file) -# datetime <- format(Sys.time(),"%Y%m%d_%H%M%S") -# myYear <- "15" -# write.table(flow.sample,paste0("SumFlow",myYear,"_",datetime,".tab"),row.names=FALSE,sep="\t") - -## ----Ion Ref, echo=FALSE, results='asis'-------------------------------------- -knitr::kable(MBSS.Ion.Ref) - -## ----Ion Data, eval=TRUE, echo=FALSE, results='asis'-------------------------- -knitr::kable(head(MBSS.Ion.Data)) - -## ----Ion Example, echo=TRUE, results='asis', warnings=FALSE------------------- -library(MBSStools) -# Load Data -data.ion <- MBSS.Ion.Data -# Load Reference Table -ref.ion <- MBSS.Ion.Ref -# Calculate Percent Contribution by Ion (data table only) -contrib.ion <- IonContrib(data.ion) -#knitr::kable(head(contrib.ion)) - -## ----Ion Results and Charts, echo=TRUE, results="hide", fig.show='hold'------- -# Load Data -data.ion <- MBSS.Ion.Data -# Load Reference Table -ref.ion <- MBSS.Ion.Ref -# Calculate Percent Contribution by Ion (data table only) -contrib.ion <- IonContrib(data.ion) -#View(contrib.ion) -# Calculate Percent Contribution by Ion (data table and reference table) -contrib.ion.2 <- IonContrib(data.ion, ref.ion) -#View(contrib.ion.2) -# Calculate Percent Contribution by Ion (data table, reference table, and conductivity values) -# ## add dummy conductivity values for each sample -# myCond <- "Cond" -# data.ion[,myCond] <- 4000 -# contrib.ion.3 <- IonContrib(data.ion, ref.ion, myCond) -# View(contrib.ion.3) -# Save Results (use write.table()) -# Plot Results -myIons <- c("Chloride (mg/L)", "Bromide (mg/L)", "Nitrate-N (mg/L)", "Sulfate (mg/L)", "Sodium (mg/L)", - "Potassium (mg/L)", "Magnesium (mg/L)", "Calcium (mg/L)" ) -myIons.Contrib <- paste0("PctContrib.",myIons) -mySite <- "BELK-101-X" -data.plot <- subset(contrib.ion, contrib.ion[,"Site"]==mySite, select=c("Site","Cond.Total",myIons.Contrib,myIons)) -## Plot, one site (with cond value) -dotchart(as.numeric(as.vector(data.plot[,myIons.Contrib])), labels=myIons, main=mySite, xlab="Percent Contribution", pch=19, pt.cex=1.2) -mtext(paste0("Conductivity (uS/cm) = ",round(data.plot[,"Cond.Total"],1))) -## Plot all sites using panel.dotplot() in the lattice package -# -## Plot as a horizontal bar plot -# need to change margins to fit labels -#par(mai=c(1,2,1,1)) -barplot(as.numeric(as.vector(data.plot[,myIons.Contrib])), names.arg=myIons, main=mySite, xlab="Percent Contribution" - , axes=TRUE, horiz=TRUE, las=1) -mtext(paste0("Conductivity (uS/cm) = ",round(data.plot[,"Cond.Total"],1))) - -## ----PHI Input, echo=FALSE, results='asis'------------------------------------ -x <- MBSS.PHI -knitr::kable(head(x)) - -## ----PHI Results, echo=TRUE--------------------------------------------------- -library(MBSStools) -# data -myData <- MBSS.PHI -# calculate PHI -PHI <- PHIcalc(myData) -knitr::kable(head(PHI)) - -## ----runShiny, echo=TRUE, eval=FALSE------------------------------------------ -# library(MBSStools) -# runShiny() - diff --git a/doc/MBSStools_vignette.html b/doc/MBSStools_vignette.html deleted file mode 100644 index 8669c96..0000000 --- a/doc/MBSStools_vignette.html +++ /dev/null @@ -1,2622 +0,0 @@ - - - - - - - - - - - - - - - - -MBSStools - an R toolkit for the MBSS program’s data needs - - - - - - - - - - - - - - - - - - - - - - - -

MBSStools - an R toolkit for the MBSS program’s data needs

-

-

2020-06-30

- - - -
-

Introduction

-

MBSStools was created by Tetra Tech, Inc. in 2017 to meet the needs of Maryland Department of Natural Resources (DNR), Maryland Biological Stream Survey (MBSS) staff to complete data manipulations in an efficient and reproducible manner.

-

It is envisioned that this library will be a living program and will add additional functions and routines in the future.

-

Many of the examples in this vignette are included in the example sections in the corresponding functions. Each function in the MBSStools library includes example data from MBSS.

-
-
-

Installation

-

The R library is saved on GitHub (https://github.com/leppott/MBSStools) for ease of updating and distribution. Issues can be tracked, fixed, and code is available for download. Current users of MBSStools can update the library using the same code used to install the library (see below). Devtools is required to download from GitHub. At this time, there are no plans to submit MBSStools to CRAN (R’s library repository).

-
install.packages("devtools")
-library(devtools)
-install_github("leppott/MBSStools")
-

To contact the author directly email .

-
-
-

Packages

-

Serveral packages were used to build the functionality in MBSStools.

-
    -
  1. FlowSum; no extra packages

  2. -
  3. IonContrib; no extra packages

  4. -
  5. MapTaxaObs; readxl and rgdal

  6. -
  7. metric.scores; dplyr

  8. -
  9. metric.values; dplyr

  10. -
  11. PHIcalc; no extra packages

  12. -
-

These packages should install automatically when MBSStools installs. But if you encounter issues with a function not working ensure that the necessary package dependencies are installed.

-

To install packages follow the example of the code below for installing dplyr.

-
install.package("dplyr")
-
-
-

Contents

-

There are several functions included in the library each with a particular focus on a dataset and the necessary calculations for data analysis.

-
    -
  1. Index of Biological Integrity (IBI) calculations for fish and benthic macroinvertebrates.

  2. -
  3. Taxonomic distribution maps for fish.

  4. -
  5. Stream discharge calculation.

  6. -
  7. Ion contribution to conductivity.

  8. -
  9. Physical Habitat Index (PHI) calculation.

  10. -
-

Example data included with each function.

-
-

IBI

-

MBSStools calculates both the benthic macroinvertebrate IBI (BIBI) and fish IBI (FIBI). THe IBIs are described in the document Southerland et al. 2005 that is included in the /extdata folder of the library.

-

There are two functions; metric.values() to calculate the metrics (e.g., total individuals or total taxa) and metric.scores() that converts the metric values to the appropriate score (e.g., 1, 3, or 5). The functions are the save for fish and benthic macroinvertebrates. Only the argument fun.Community needs to be changed to “bugs” or “fish”.

-

MBSStools does not aggregate or compile taxa lists. Taxa data with site/sample information, counts, phylogenetic (phylum, class, order, etc), and autecological (habit, tolerance value, and function feeding group) information is required as an input to the functions. Fish data needs the additional values of watershed (catchment) area (in acres), average stream width, and reach length.

-

In background is a file (/data-raw/metrics.scoring.tab) wiht a table of metric names, scoring thresholds, index name, and index regions. These can be changed to modify the index names, bioregions, metric names, and scoring thresholds. This table can be modified and used as input into the function. For simplicity this table is included by default.

-

The functions metric.values() and metric.scores() require the dplyr function.

-
-

IBI, Fish

-

Calculates the fish IBI.

-

The adjustment of metrics based on watershed area is automatic for fish metrics.

-

Fish metric values assumes the following fields (all upper case)

-
    -
  • SITE = MBSS sample identifier.

  • -
  • FIBISTRATA = Fish region (COASTAL, EPIEDMONT, WARM, COLD).

  • -
  • ACREAGE = Catchment area in acres.

  • -
  • LEN_SAMP = Length of stream sampled; typically 75-meters.

  • -
  • AVWID = Average stream width (meters) for sampled site.

  • -
  • SPECIES = MBSS fish taxa name.

  • -
  • TOTAL = Number of fish collected in sample.

  • -
  • TYPE = Fish group identifier (ALL CAPS); SCULPIN, DARTER, MADTOM, etc.

  • -
  • TROPHIC_MBSS = MBSS tropic status designations (ALL CAPS); OM, GE, IS, IV, etc.

  • -
  • PTOLR = Pollution tolerance level (ALL CAPS); T, I, NO TYPE.

  • -
-
# Metrics, Fish
-library(MBSStools)
-#(generate values then score)s
-myIndex <- "MBSS.2005.Fish"
-# Thresholds
-thresh <- metrics_scoring
-# get metric names for myIndex
-(myMetrics.Fish <- as.character(droplevels(unique(thresh[thresh[,"Index.Name"]==myIndex,"MetricName.Other"]))))
-
##  [1] "ABUNSQM"   "NUMBENTSP" "PTOL"      "PGEOMIV"   "PROUND"    "PABDOM"   
-##  [7] "BIOM_MSQ"  "P_LITH"    "P_IS"      "PBROOK"    "PSCULP"
-
# Taxa Data
-myDF.Fish <- taxa_fish
-myMetric.Values.Fish <- metric.values(myDF.Fish, "fish", myMetrics.Fish, TRUE)
-#View(myMetric.Values.Fish)
-# SCORE
-Metrics.Fish.Scores <- metric.scores(myMetric.Values.Fish, myMetrics.Fish, "Index.Name", "FIBISTRATA", thresh)
-
## One or more fish samples (n = 1) had zero organisms and was scored as a 1 (metrics and IBI).
-
# View Results
-knitr::kable(head(Metrics.Fish.Scores))
- ------------------------------------------------ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Index.NameSITEFIBISTRATAACREAGELEN_SAMPAVWIDSTRMAREATOTCNTABUNSQMPABDOMTOTBIOMBIOM_MSQNUMBENTSPNUMBROOKPBROOKNUMGEOMIVPGEOMIVNUMISP_ISNUMLITHP_LITHNUMROUNDPROUNDNUMSCULPPSCULPNUMTOLPTOLNUMBENTSP_ObsNUMBENTSP_mNUMBENTSP_bNUMBENTSP_ExpNUMBENTSP_AdjIndex.RegionSC_ABUNSQMSC_NUMBENTSPSC_PTOLSC_PGEOMIVSC_PROUNDSC_PABDOMSC_BIOM_MSQSC_P_LITHSC_P_ISSC_PBROOKSC_PSCULPsum_IBIIBI
MBSS.2005.Fish_TESTCOASTAL10.0000755.000375.00000.00000000.0000000.0000000.00000000000.000000000.00000000000.0000001.69-3.33-1.64000000.0000000COASTAL1111110000061.000000
MBSS.2005.FishCHGX-432-S-1111EPIEDMONT273.0000751.500112.500540.4800000100.000001601.4222220.00000000054100.000000000.00000000054100.0000001.25-2.360.68520330.0000000EPIEDMONT3111001100081.333333
MBSS.2005.FishCHGX-435-R-1111EPIEDMONT416.1001753.500262.5005392.053333371.24304295711.2647620.00000000051495.361780015528.75696000051495.3617801.25-2.360.91399730.0000000EPIEDMONT51130051000162.666667
MBSS.2005.FishCHGX-537-R-1111EPIEDMONT820.6357752.025151.8751040.684773760.576924552.9958850.00000000010096.15385003836.5384600009086.5384601.25-2.361.28268800.0000000EPIEDMONT31130013000122.000000
MBSS.2005.FishCHGX-546-R-1111EPIEDMONT1732.0084753.425256.8751390.541119240.28777307811.9824820.5923513008359.71223007654.6762600006043.1654711.25-2.361.68818750.5923513EPIEDMONT35550053000264.333333
MBSS.2005.FishCHGX-648-S-1111EPIEDMONT3805.0000758.950671.2502930.436499131.3993250207.4785850.47271420020168.600680014148.12287000013847.0989811.25-2.362.11544330.4727142EPIEDMONT35350033000223.666667
-
-
-

IBI, Benthic Macroinvertebrates, MBSS

-

Bug metric values assumes the following fields (all upper case)

-
    -
  • SITE = MBSS sample identifier.

  • -
  • TAXON = MBSS benthic macroinvertebrate name.

  • -
  • N_TAXA = Number of taxon collected in sample.

  • -
  • EXCLUDE = Non-unique taxa (i.e., parent taxon with one or more children taxa present in sample). “Y” = do not include in taxa richness metrics. * STRATA_R = Benthic macroinvertebrate region (COASTAL, EPIEDMONT, or HIGHLAND).

  • -
  • Phylogenetic fields

  • -
  • (PHYLUM), CLASS, ORDER, FAMILY, GENUS, OTHER_TAXA, TRIBE, FFG, HABIT, FINALTOLVAL07

  • -
-

Valid values for FFG: col, fil, pre, scr, shr

-

Valid values for HABIT: BU, CB, CN, SP, SW

-

MSW data should be first combined to family level and EXCLUDE recalculated.

-

Additional fields needed:

-
    -
  • FAM_TV (need to include all the same fields, just leave blank).
  • -
-

In addition to the metric scores a QC check on samples with too many (>120) or too few (<60) organisms is returned in the results. Those with more than the maximum (120) should be subsampled down to within the target range.

-
# Metrics, Index, Benthic Macroinvertebrates, genus
-# (generate values then scores)
-myIndex <- "MBSS.2005.Bugs"
-# Thresholds
-thresh <- metrics_scoring
-# get metric names for myIndex
-(myMetrics.Bugs.MBSS <- as.character(droplevels(unique(thresh[thresh[,"Index.Name"]==myIndex,"MetricName.Other"]))))
-
##  [1] "ntaxa"      "nept"       "nephem"     "pintol_urb" "pephem"    
-##  [6] "nscrape"    "pclimb"     "pchiron"    "pcling"     "ptany"     
-## [11] "pscrape"    "pswim"      "pdipt"
-
# Taxa Data
-myDF.Bugs.MBSS <- taxa_bugs_genus
-myMetric.Values.Bugs.MBSS <- metric.values(myDF.Bugs.MBSS, "bugs", myMetrics.Bugs.MBSS)
-#View(myMetric.Values.Bugs.MBSS)
-# SCORE
-Metrics.Bugs.Scores.MBSS <- metric.scores(myMetric.Values.Bugs.MBSS, myMetrics.Bugs.MBSS, "INDEX.NAME", "STRATA_R", thresh)
-
## One or more bug samples had < 60 (n = 0) or > 120 (n = 90) organisms.
-## These samples should be further examined.
-
# View Results
-#View(Metrics.Bugs.Scores.MBSS)
-
-# QC bug count
-Metrics.Bugs.Scores.MBSS[Metrics.Bugs.Scores.MBSS[,"totind"]>120,"QC_Count"] <- "LARGE"
-Metrics.Bugs.Scores.MBSS[Metrics.Bugs.Scores.MBSS[,"totind"]<60,"QC_Count"] <- "SMALL"
-Metrics.Bugs.Scores.MBSS[is.na(Metrics.Bugs.Scores.MBSS[,"QC_Count"]),"QC_Count"] <- "OK"
-# table of QC_Count
-knitr::kable(head(Metrics.Bugs.Scores.MBSS))
- -------------------------------------------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SITESTRATA_RINDEX.NAMEtotindntaxaneptnephemtotephemnscrapetotclimbtotchirontotclingtottanytotscrapetotswimtotdipttotintol_urbpephempclimbpchironpclingptanypscrapepswimpdiptpintol_urbndiptnintolbecksnintol_FAMIndex.NameIndex.RegionSC_ntaxaSC_neptSC_nephemSC_pintol_urbSC_pephemSC_nscrapeSC_pclimbSC_pchironSC_pclingSC_ptanySC_pscrapeSC_pswimSC_pdiptsum_IBIIBIQC_Count
CHGX-432-S-1111EPIEDMONTMBSS.2005.Bugs125271011343150822913574510.40000024.80000040.0000065.600001.6000007.20000010.40000045.6000036.000001110186MBSS.2005.BugsEPIEDMONT5313000330000183.000000LARGE
CHGX-435-R-1111EPIEDMONTMBSS.2005.Bugs119172001981392308500.0000007.56302568.0672332.773111.6806722.5210080.00000071.428570.0000011000MBSS.2005.BugsEPIEDMONT3111000130000101.666667OK
CHGX-537-R-1111EPIEDMONTMBSS.2005.Bugs1212910412618408212121150169.91735514.87603333.0578567.768609.9173559.9173559.09090941.3223113.22314118145MBSS.2005.BugsEPIEDMONT5353000330000223.666667LARGE
CHGX-546-R-1111EPIEDMONTMBSS.2005.Bugs129278223422289701123371417.82945717.05426421.7054375.193800.0000008.52713217.82945728.6821710.85271117157MBSS.2005.BugsEPIEDMONT5331000550000223.666667LARGE
CHGX-648-S-1111EPIEDMONTMBSS.2005.Bugs1162713440632318021435382634.48275927.58620726.7241468.965521.72413812.06896530.17241432.7586222.413791012208MBSS.2005.BugsEPIEDMONT5553000330000244.000000OK
EBUX-435-S-1111EPIEDMONTMBSS.2005.Bugs13737155405153498121339467829.19708010.94890524.8175271.532858.7591249.48905128.46715333.5766456.9343116193810MBSS.2005.BugsEPIEDMONT5555000330000264.333333LARGE
-
-
-

IBI, Benthic Macroinvertebrates, MSW

-

The Maryland Stream Wader index is from Stribling et al. 1999. Family level identifications need to be provided by the user. Metric values and scores shown below for example data. This index has only two bioregions (CP = Coastal Plain and NCP = Non-Coastal Plain).

-
# Metrics, MSW Index, Benthic Macroinvertebrates, family
-myIndex <- "MSW.1999.Bugs"
-# Thresholds
-thresh <- metrics_scoring
-# get metric names for myIndex
-(myMetrics.Bugs.MSW <- as.character(droplevels(unique(thresh[thresh[,"Index.Name"]==myIndex,"MetricName.Other"]))))
-
## [1] "ntaxa"      "nept"       "nephem"     "ndipt"      "pephem"    
-## [6] "nintol_FAM" "becks"
-
# Taxa Data
-myDF.Bugs.MSW <- taxa_bugs_family
-myMetric.Values.Bugs.MSW <- metric.values(myDF.Bugs.MSW, "bugs", myMetrics.Bugs.MSW)
-#View(myMetric.Values.Bugs.MSW)
-# SCORE
-Metrics.Bugs.Scores.MSW <- metric.scores(myMetric.Values.Bugs.MSW, myMetrics.Bugs.MSW, "INDEX.NAME", "STRATA_R", thresh)
-
## One or more bug samples had < 60 (n = 0) or > 120 (n = 102) organisms.
-## These samples should be further examined.
-
# View Results
-knitr::kable(head(Metrics.Bugs.Scores.MSW))
- ------------------------------------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SITESTRATA_RINDEX.NAMEtotindntaxaneptnephemtotephemnscrapetotclimbtotchirontotclingtottanytotscrapetotswimtotdipttotintol_urbpephempclimbpchironpclingptanypscrapepswimpdiptpintol_urbndiptnintolbecksnintol_FAMIndex.NameIndex.RegionSC_ntaxaSC_neptSC_nephemSC_ndiptSC_pephemSC_nintol_FAMSC_beckssum_IBIIBI
CHGX-432-S-1111NCPMSW.1999.Bugs1251671130050000057010.400000040.00000000045.6000003135MSW.1999.BugsNCP5315331213.000000
CHGX-435-R-1111NCPMSW.1999.Bugs1197100008100008500.000000068.06723000071.4285703130MSW.1999.BugsNCP1115111111.571429
CHGX-537-R-1111NCPMSW.1999.Bugs121188312004000005009.917355033.05785000041.3223103135MSW.1999.BugsNCP5355331253.571429
CHGX-546-R-1111NCPMSW.1999.Bugs1291762230028000037017.829457021.70543000028.6821704136MSW.1999.BugsNCP5335331233.285714
CHGX-648-S-1111NCPMSW.1999.Bugs11618114400031000038034.482759026.72414000032.7586203138MSW.1999.BugsNCP5555551314.428571
EBUX-435-S-1111NCPMSW.1999.Bugs13719103400034000046029.197080024.81752000033.5766404139MSW.1999.BugsNCP5555551314.428571
-
-
-
-

Fish Distribution Maps

-

The intent of this function is to recreate the taxa distribution maps on the MBSS websitehttp://eyesonthebay.dnr.maryland.gov/mbss/fishes.cfm. The maps for all taxa can be generated from a single line of code and then given to the web site maintainers as replacements.

-

The maps for all taxa can be generated from a single line of code and then given to the web site maintainers as replacements. The maps generated with this function use a ‘crosswalk’ table that converts taxa names to map names.

-

The function MapTaxaObs() requires the readxl and rgdal packages.

-
-

Data inputs

-

The user will need GIS files for the state of Maryland for State, County, and Water.

-

The inputs for this function, besides the three GIS shapefiles, are taxa observations and a taxa name crosswalk (translation) table between taxa names and map names.

-

All inputs are included in the MBSStools library and can be copied to the current directory with the code below.

-
# Set Working Directory
-wd <- getwd()
-# Create Example Data if Needed
-## Create Directories
-myDir.create <- file.path(wd,"Data")
-ifelse(dir.exists(myDir.create)==FALSE,dir.create(myDir.create),"Directory already exists")
-myDir.create <- file.path(wd,"GIS")
-ifelse(dir.exists(myDir.create)==FALSE,dir.create(myDir.create),"Directory already exists")
-myDir.create <- file.path(wd,"Maps")
-ifelse(dir.exists(myDir.create)==FALSE,dir.create(myDir.create),"Directory already exists")
-## Create Data
-### Taxa Data
-myFiles <- c("AllFish_95to16.xls", "TaxaMapsCrossWalk20170731.xlsx")
-file.copy(file.path(path.package("MBSStools"),"extdata",myFiles),file.path(wd,"Data",myFiles))
-### GIS
-unzip(file.path(path.package("MBSStools"),"extdata","MD_GIS.zip"),exdir=file.path(wd,"GIS"))
-
-
-

Example Input Data

-

Observation data with three columns needed for the tool to work (common name, latitude, and longitude). Additional columns can be appended (e.g., SiteYr) and will not affect the functionality.

-
##             CommonName Latitude83 Longitude83
-## 1    eastern mudminnow     39.055   -76.73417
-## 2           creek chub     39.055   -76.73417
-## 3      channel catfish     39.055   -76.73417
-## 4        glassy darter     39.055   -76.73417
-## 5 eastern mosquitofish     39.055   -76.73417
-## 6        golden shiner     39.055   -76.73417
-

Crosswalk data with common name and map name.

-
##         CommonName  MapName
-## 1          alewife  alewife
-## 2     american eel  amereel
-## 3    american shad amershad
-## 4    banded darter bandartr
-## 5 banded killifish bankilli
-## 6    black crappie blkcrapi
-
-
-
-

Map Creation

-

The code below can be used to generate the maps (n=131) associated with the 1995 to 2016 data. Any taxa without a match in the crosswalk table (n=54) are listed in a CSV file and the number reported to the user in the R console but maps are not generated (by default). If the user wants all maps then the parameter ‘onlymatches’ should be set to ‘FALSE’ (as in the example below).

-
# Set Working Directory
-wd <- getwd()
-
-# Inputs
-Obs <- "AllFish_95to16.xls"
-XWalk <- "TaxaMapsCrossWalk20170731.xlsx"
-wd <- getwd()
-
-# Create maps
-MapTaxaObs(Obs, XWalk, wd, onlymatches = FALSE)
-

The intent behind this function was to recreate the fish taxa distribution maps. But the data inputs are not specific to fish and can be used for benthic macroinvertebrate data.

-

The taxa distribution map for brown trout is shown below.

-
## Loading required package: sp
-
## rgdal: version: 1.5-12, (SVN revision 1018)
-## Geospatial Data Abstraction Library extensions to R successfully loaded
-## Loaded GDAL runtime: GDAL 3.0.4, released 2020/01/28
-## Path to GDAL shared files: C:/Programs/R/R-4.0.0/library/rgdal/gdal
-## GDAL binary built with GEOS: TRUE 
-## Loaded PROJ runtime: Rel. 6.3.1, February 10th, 2020, [PJ_VERSION: 631]
-## Path to PROJ shared files: C:/Programs/R/R-4.0.0/library/rgdal/proj
-## Linking to sp version:1.4-2
-## To mute warnings of possible GDAL/OSR exportToProj4() degradation,
-## use options("rgdal_show_exportToProj4_warnings"="none") before loading rgdal.
-

-
-
-

Stream Discharge

-

Calculate stream discharge based on field measurements. Side channels that are properly identified in the data will be included.

-

The function FlowSum() requires the no additional packages.

-
library(MBSStools)
-# data
-MBSS.flow <- MBSS.flow
-# calculate flow
-flow.cell <- FlowSum(MBSS.flow, returnType="cell")
-flow.sample <- FlowSum(MBSS.flow)
-# examine data
-View(flow.cell)
-View(flow.sample)
-# Example Save file (tab delimited text file)
-datetime <- format(Sys.time(),"%Y%m%d_%H%M%S")
-myYear <- "15"
-write.table(flow.sample,paste0("SumFlow",myYear,"_",datetime,".tab"),row.names=FALSE,sep="\t")
-
-
-

Ion Matrix

-

The IonContrib() function calculates conductivity contribution from provided ion concentrations using Kohlrausch’s Law. If a total conductivity measurement is not provided the total conductivity is calculated as the sum of all ions present in the data. If the user provides a conductivity measurement then ion contributions are a percentage of that number. In the latter case “Other” is added as an ion to capture any percentage of total conductivity not represented by the provided ions. Plotting is done outside of this function.

-

Data will need to be in “wide” format. That is, a single record for each sample and the ions to be analyzed in columns.

-

A reference table of ions and their equivalent ionic conductance at infinite dilution is provided with the function as “MBSS.Ion.Ref”. The function allows for input of a user supplied data frame if this table needs updating with more ions.

-

The function IonContrib() requires the no additional packages.

- ---------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameIonSymbolMolecular Weight (g/mole)ValanceEquivalent Ionic conductance at infinite dilution (µS/cm)MultiplierSortOrder
Calcium (mg/L)CalciumCa2+40.07800259.472.96771301
Magnesium (mg/L)MagnesiumMg2+24.30500253.004.36124252
Sodium (mg/L)SodiumNa+22.98977150.082.17836043
Potassium (mg/L)PotassiumK+39.09830173.481.87936564
Bicarbonate (mg/L)BicarbonateHCO3-61.01714144.500.72930335
Sulfate (mg/L)SulfateSO42-96.06360280.001.66556326
Chloride (mg/L)ChlorideCl-35.45270176.312.15244547
Iron (II) (mg/L)Iron (II)Fe2+55.84700254.001.93385508
Iron (III) (mg/L)Iron (III)Fe3+55.84700368.003.65283729
Bromide (mg/L)BromideBr-79.90400178.100.977422910
Strontium (mg/L)StrontiumSr2+87.62000259.401.355854811
Nitrate-N (mg/L)Nitrate-NNO3-14.00674171.425.098973812
Barium (mg/L)BariumBa2+137.32700263.600.926256313
-

The columns for the ions need to match the reference table names. The function IonContrib() includes a reference table that is used by default but the user can supply their own reference table.

- ---------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SiteStream NameSHA Road CrossingIon MatrixDate CollectedTime CollectedChloride (mg/L)Bromide (mg/L)Nitrate-N (mg/L)Sulfate (mg/L)Sodium (mg/L)Potassium (mg/L)Magnesium (mg/L)Calcium (mg/L)
BELK-101-XGramies RunMD 273 (Telegraph Rd.)Pre-Application Baseline2016-12-141899-12-30 10:48:0040.98540.02550.620911.213919.361.8978.15312.11
BELK-102-XGramies RunMD 273 (Telegraph Rd.)Pre-Application Baseline2016-12-141899-12-30 10:59:0036.22140.02440.523613.529516.082.1039.40314.09
BELK-301-XBig Elk CreekMD 273 (Telegraph Rd.)Pre-Application Baseline2016-12-141899-12-30 09:15:0031.37820.02764.869313.598714.063.1666.90615.73
BELK-302-XBig Elk CreekMD 273 (Telegraph Rd.)Pre-Application Baseline2016-12-141899-12-30 09:19:0030.40180.02804.547413.722414.013.0496.58315.92
BRIG-301-XPatuxent RiverMD 94 (Woodbine Rd.)Pre-Application Baseline2016-12-131899-12-30 14:53:0037.20930.02323.09274.289119.022.0205.97710.99
BRIG-302-XPatuxent RiverMD 94 (Woodbine Rd.)Pre-Application Baseline2016-12-131899-12-30 15:02:0037.67890.02153.08694.285418.622.0355.95811.00
-

Example code is below. The user would then save the output (e.g., write.csv()).

-
library(MBSStools)
-# Load Data
-data.ion <- MBSS.Ion.Data
-# Load Reference Table
-ref.ion <- MBSS.Ion.Ref
-# Calculate Percent Contribution by Ion (data table only)
-contrib.ion <- IonContrib(data.ion)
-

No conductivity values provided.
-Ion contributions calculated from the sum of calculated ion conductivity values.

-
#knitr::kable(head(contrib.ion))
-

Dot charts are a good way to display the data. But any chart of the user’s preference can be used.

-
# Load Data
-data.ion <- MBSS.Ion.Data
-# Load Reference Table
-ref.ion <- MBSS.Ion.Ref
-# Calculate Percent Contribution by Ion (data table only)
-contrib.ion <- IonContrib(data.ion)
-#View(contrib.ion)
-# Calculate Percent Contribution by Ion (data table and reference table)
-contrib.ion.2 <- IonContrib(data.ion, ref.ion)
-#View(contrib.ion.2)
-# Calculate Percent Contribution by Ion (data table, reference table, and conductivity values)
-# ## add dummy conductivity values for each sample
-# myCond <- "Cond"
-# data.ion[,myCond] <- 4000
-# contrib.ion.3 <- IonContrib(data.ion, ref.ion, myCond)
-# View(contrib.ion.3)
-# Save Results (use write.table())
-# Plot Results
-myIons <- c("Chloride (mg/L)", "Bromide (mg/L)", "Nitrate-N (mg/L)", "Sulfate (mg/L)", "Sodium (mg/L)",
-     "Potassium (mg/L)", "Magnesium (mg/L)",  "Calcium (mg/L)" )
-myIons.Contrib <- paste0("PctContrib.",myIons)
-mySite <- "BELK-101-X"
-data.plot <- subset(contrib.ion, contrib.ion[,"Site"]==mySite, select=c("Site","Cond.Total",myIons.Contrib,myIons))
-## Plot, one site (with cond value)
-dotchart(as.numeric(as.vector(data.plot[,myIons.Contrib])), labels=myIons, main=mySite, xlab="Percent Contribution", pch=19, pt.cex=1.2)
-mtext(paste0("Conductivity (uS/cm) = ",round(data.plot[,"Cond.Total"],1)))
-## Plot all sites using panel.dotplot() in the lattice package
-#
-## Plot as a horizontal bar plot
-# need to change margins to fit labels
-#par(mai=c(1,2,1,1))
-barplot(as.numeric(as.vector(data.plot[,myIons.Contrib])), names.arg=myIons, main=mySite, xlab="Percent Contribution"
-       , axes=TRUE, horiz=TRUE, las=1)
-mtext(paste0("Conductivity (uS/cm) = ",round(data.plot[,"Cond.Total"],1)))
-

-
-
-

PHI

-

The PHIcalc() function calculates the MBSS Physical Habitat Index (PHI), Paul et al. 2003. The report is included in the /extdata folder of the library.

-

There are two versions of the calculation based on pre- and post-2000. The function determines the correct calculation based on the data provided.

-

The input is a data frame with column names matching the variables collected in the field along with SampleID, bioregion, and area (acres).

-

The function PHIcalc() requires the no additional packages.

- ---------------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
StationIDSampleIDCollDateBioRegionPHICalcYearArea_acresRemote_020Shading_0100EpiSub_020BankStab_020AvgRipWid_m50maxInStrmHab_020InstrmWood_NumRiffQual_020Embedd_0100Erosn_ExtR_075Erosn_ExtL_075Erosn_SevR_03Erosn_SevL_03RoadDist_m
AL-A-007-304-96NANAHighlands1994.0000008009.002.000000807.0000001250NANANANANANANANANA
AL-A-020-228-95NANAHighlands1994.0000001335.2617.000000901.000000550NANANANANANANANANA
AL-A-027-205-95NANAHighlands1994.0000002185.6520.0000009311.0000001650NANANANANANANANANA
AL-A-027-209-95NANAHighlands1994.0000002428.1119.0000009711.0000001550NANANANANANANANANA
AL-A-033-314-95NANAHighlands1994.0000009142.736.0000006017.000000650NANANANANANANANANA
AL-A-054-320-96NANAHighlands1994.00000038907.001.000000605.000000160NANANANANANANANANA
-

The function returns a dataframe of reslts that need to be saved (e.g., write.table()). The result table from the example data is shown below.

-
library(MBSStools)
-# data
-myData <- MBSS.PHI
-# calculate PHI
-PHI <- PHIcalc(myData)
-knitr::kable(head(PHI))
- ---------------------------------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
StationIDSampleIDCollDateBioRegionPHICalcYearArea_acresRemote_020Shading_0100EpiSub_020BankStab_020AvgRipWid_m50maxInStrmHab_020InstrmWood_NumRiffQual_020Embedd_0100Erosn_ExtR_075Erosn_ExtL_075Erosn_SevR_03Erosn_SevL_03RoadDist_mErosn_SevR_02Erosn_SevL_02BANKSTAB1994BANKSTAB2000REMOTE1994REMOTE2000REMOTESHADINGEPIBANKSTABRIPWIDINSTRHABWOODRIFFQUALEMBEDDPHI.denomPHI.sumPHI
AL-A-007-304-96NANAHighlands1994.0000008009.0028071250NANANANANANANANANANANA0.7097067NA0.10NA1075.2475438.88888970.97067100NANANANA5295.107159.02142
AL-A-020-228-95NANAHighlands1994.0000001335.2617901550NANANANANANANANANANANA0.3560104NA0.85NA8587.365145.55555635.60104100NANANANA5313.521762.70435
AL-A-027-205-95NANAHighlands1994.0000002185.652093111650NANANANANANANANANANANA0.8640553NA1.00NA10091.9754961.11111186.40553100NANANANA5439.492187.89843
AL-A-027-209-95NANAHighlands1994.0000002428.111997111550NANANANANANANANANANANA0.8274722NA0.95NA9599.9755261.11111182.74722100NANANANA5438.833887.76677
AL-A-033-314-95NANAHighlands1994.0000009142.7366017650NANANANANANANANANANANA0.4174798NA0.30NA3056.3686794.44444441.74798100NANANANA5322.561164.51222
AL-A-054-320-96NANAHighlands1994.00000038907.001605160NANANANANANANANANANANA0.8640553NA0.05NA556.3686727.77777886.405530NANANANA5175.552035.11040
-
-
-
-

Shiny

-

Included in the package is an example Shiny package to calculates the three IBI’s for MBSS.

-
library(MBSStools)
-runShiny()
-
- - - - - - - - - - - diff --git a/inst/extdata/Notebook_MBSStools.Rmd b/inst/extdata/Notebook_MBSStools.Rmd index ec7303c..0fed848 100644 --- a/inst/extdata/Notebook_MBSStools.Rmd +++ b/inst/extdata/Notebook_MBSStools.Rmd @@ -33,8 +33,8 @@ file.remove("NEWS.html") #file.remove("NEWS.md") #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Library Name -myPkg <- "MBSStools" # "ContDataQC","MMIcalc","MMIcalcNV","MBSStools","XC95" -# Load Library +myPkg <- "MBSStools" +# Load Library) library(devtools) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create Package @@ -51,7 +51,7 @@ library(devtools) devtools::document() ## Install New Package (locally) setwd("..") # return to root directory first -devtools::install(myPkg, quick=FALSE, reload=TRUE, build_vignettes = TRUE) +devtools::install(myPkg, quick=FALSE, reload=TRUE, build_vignettes = FALSE) # blank row above allows for the code to continue instead of waiting for user # response to pkg updates. diff --git a/inst/extdata/Notebook_MBSStools.nb.html b/inst/extdata/Notebook_MBSStools.nb.html index 6a7a9f9..eebb1f3 100644 --- a/inst/extdata/Notebook_MBSStools.nb.html +++ b/inst/extdata/Notebook_MBSStools.nb.html @@ -13,38 +13,1587 @@ Notebook, MBSStools - - + + - - - - + + + + - - - - - - +h1.title {font-size: 38px;} +h2 {font-size: 30px;} +h3 {font-size: 24px;} +h4 {font-size: 18px;} +h5 {font-size: 16px;} +h6 {font-size: 12px;} +code {color: inherit; background-color: rgba(0, 0, 0, 0.04);} +pre:not([class]) { background-color: white } + + + + + + +code{white-space: pre-wrap;} +span.smallcaps{font-variant: small-caps;} +span.underline{text-decoration: underline;} +div.column{display: inline-block; vertical-align: top; width: 50%;} +div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;} +ul.task-list{list-style: none;} +