This report is automatically generated with the R package knitr (version 1.40) .

source("R Functions/functions_QA data.R")


### LOAD DATA ###
DWRMeHg <- readxl::read_excel('Reeval_Impl_Goals_Linkage_Analysis/Data/Aqueous/DWR_MeHg.xlsx', sheet='Lookup for Central Valley RWQCB', guess_max = 30000)
nrow(DWRMeHg) #number of rows should match the Excel file (minus the header row)
## [1] 675
### LIST COLUMNS TO BE USED, ADD USER DEFINED COLUMNS, & RENAME COLUMNS TO CEDEN STANDARDS ###
#Use 1.READ ME.xlsx, 'ColumnsForR' to list & identify columns that match corresponding CEDEN Standard columns
keep_cols <- c('SourceID','SourceRow', 'Full Station Name', 'WQ Station Code', 'Collection Date', 'Station Type', 'Method Name', 'Constituent', 'Units', 'Result', 'RL', 'DWR Sample Code', 'Sample Description', 'DDLat', 'DDLon')


#temp_cols <- c('COLUMN NAME', 'COLUMN NAME') #Include columns that do not match CEDEN standards but may be useful (e.g., Unit columns for MDL & RL)
#temp_cols are removed before the data is merged with other datasets
  #not applicable for this dataset

DWRMeHg_new <- DWRMeHg %>%
  select( c(keep_cols) ) %>% #DO NOT CHANGE - selects columns specified above
  mutate(              #Add user defined columns
    #COLUMNNAME = 'THE SPECIFIED VALUE'
    CitationCode = 'DWRMeHg2018',
    CoordSystem = 'NAD83',
    MatrixName = 'Aqueous',
    CitationCode = "DWRMeHg",
    Project = NA,
    LabBatch = NA,
    LabSampleID = NA,
    MDL = NA_real_,
    QACode = NA,
    BatchVerification = NA,
    ComplianceCode = NA,
    CollectionComments = NA,
    ResultsComments = NA,
    BatchComments = NA,
    SampleTypeCode = NA
  ) %>%
  rename( #Rename columns to CEDEN standards
    #CEDEN 'COLUMNNAME' = DWRMeHg 'COLUMNNAME'
    #If a column doesnt match the CEDEN Standard, delete that column below, talk to Robin and discuss if we can add it using other information
    #If a column below doesn't exist; move COLUMNNAME to Mutate above using format; StationName = NA_character_
    'StationName' = 'Full Station Name',
    'StationCode' = 'WQ Station Code',
    'SampleDate' = 'Collection Date',
    'WBT' = 'Station Type',
    'Unit' = 'Units',
    'MethodName' = 'Method Name',
    'Analyte' = 'Constituent',
    'SampleID' = 'DWR Sample Code',
    'SampleComments' = 'Sample Description',
    'TargetLatitude' = 'DDLat',
    'TargetLongitude' = 'DDLon'
    )
nrow(DWRMeHg_new)
## [1] 675
#View(DWRMeHg_new)

### FORMAT COLUMN PARAMETERS ###

  # Standardize WBT (WaterBodyType) Groups - "River/Stream", "Drain/Canal", "Wetland", "Not Recorded" #
unique(DWRMeHg_new$WBT) #Identifies OLDNAMES
## [1] "Broad Water Body" "River and Stream" "General (UTM)"
#Look for inconsistent group pairings between MatrixName and WBT (e.g., 'Soil; Stream')
unique(paste(DWRMeHg_new$MatrixName, DWRMeHg_new$WBT, sep='; '))
## [1] "Aqueous; Broad Water Body" "Aqueous; River and Stream" "Aqueous; General (UTM)"
#If an inconsistent grouping exists, add comment to 'CollectionComments' column using code:  mutate(CollectionComments = case_when(MatrixName=='CONDITION' ~ 'COMMENT', TRUE ~ MatrixName)), 
#STANDARD CODE TO CHANGE GROUPING NAMES
DWRMeHg_new <- DWRMeHg_new %>%
  mutate(WBT = recode(WBT,
                      "River and Stream" = "River/Stream",
                      "General (UTM)" = "Not Recorded",
                      "Broad Water Body" = "Not Recorded")
         )
unique(paste(DWRMeHg_new$MatrixName, DWRMeHg_new$WBT, sep='; ')) #New naming structure for Matrix Name & WBT Groupings
## [1] "Aqueous; Not Recorded" "Aqueous; River/Stream"
  # Standardize Analyte Groups - "Mercury, Total", "Mercury, Dissolved", "Mercury, Suspended", & same for Methylmercury #
unique(DWRMeHg_new$Analyte) #IF ANALYTE IS IN 2 COLUMNS e.g., (Hg & MeHg); (Total, Dissolved, Suspended) SEE WQP SCRIPT FOR EXAMPLE
## [1] "Total Methylmercury"     "Dissolved Methylmercury"
DWRMeHg_new <- DWRMeHg_new %>%
  mutate(Analyte = recode(Analyte,
                          "Total Methylmercury" = "Methylmercury, Total",
                          "Dissolved Methylmercury" = "Methylmercury, Dissolved"
                              )
         )
unique(DWRMeHg_new$Analyte)
## [1] "Methylmercury, Total"     "Methylmercury, Dissolved"
  # Format Result Column to Numeric#
  # Check column for text - based on text user needs to decide what to do
if(any(grepl('<|[a-df-zA-DF-Z]',DWRMeHg_new$Result))){
  old <-DWRMeHg_new$Result
  new <-DWRMeHg_new$Result
  new[grepl('<|[a-df-zA-DF-Z]', new)] <- NA #skip 'e' for exponential notation e.g., "8e-005"
  #Print what text was found and what is being done
  cat(paste0("'Result' column should be numeric but some cells contain ", grammaticList(setdiff(old, new)), ".\n '<RL in 'Result, altered to standardize to 'ND'.\n"))
  DWRMeHg_new <- DWRMeHg_new %>%
    mutate(
      ResultQualCode = if_else(Result=="< R.L.", "DNQ", "="),  # checked data spreadsheet that using a default of "=" was ok.
      Result = if_else(Result=="< R.L.", NA_character_, Result),
      Result = as.numeric(Result)
      )

} else {
  cat("'Result' column converted to numeric format\n")
  DWRMeHg_new$Result <- as.numeric(DWRMeHg_new$Result)}
## 'Result' column should be numeric but some cells contain < R.L..
##  '<RL in 'Result, altered to standardize to 'ND'.
  # Format MDL Column to Numeric#
  # Check column for text - based on text user needs to decide what to do
if(!is.numeric(DWRMeHg_new$MDL)){   #alternate logic: if(any(grepl('[a-df-zA-DF-Z]',DWRMeHg_new$MDL)))
  old <-DWRMeHg_new$MDL
  new <-DWRMeHg_new$MDL
  new[grepl('[a-df-zA-DF-Z]', new)] <- NA #skip 'e' for exponential notation e.g., "8e-005"
  #Print what text was found and what is being done
  cat(paste0("'Result' column should be numeric but some cells contain ", grammaticList(setdiff(old, new)),
             ".\nACTIONS TAKEN:\n",
             "~explain here~.\n"))
  #DWRMeHg_new <- DWRMeHg_new %>%
  #  mutate( #Due stuff to prep column to be converted to Numeric
  #    MDL = as.numeric(new)
  #  )
} else {
  cat("'MDL' column is in numeric format")}
## 'MDL' column is in numeric format
  # Format RL Column to Numeric#
  # Check column for text - based on text user needs to decide what to do
if(!is.numeric(DWRMeHg_new$RL)){   #alternate logic: if(any(grepl('[a-df-zA-DF-Z]',DWRMeHg_new$RL)))
  old <-DWRMeHg_new$RL
  new <-DWRMeHg_new$RL
  new[grepl('[a-df-zA-DF-Z]', new)] <- NA #skip 'e' for exponential notation e.g., "8e-005"
  #Print what text was found and what is being done
  cat(paste0("'Result' column should be numeric but some cells contain ", grammaticList(setdiff(old, new)),
             ".\nACTIONS TAKEN:\n",
             "~explain here~.\n"))
  #DWRMeHg_new <- DWRMeHg_new %>%
  #  mutate( #Due stuff to prep column to be converted to Numeric
  #    RL = as.numeric(new)
  #  )
} else {
  cat("'RL' column is in numeric format\n")}
## 'RL' column is in numeric format
  # Check if Result, MDL, & RL Columns all equal <NA> or 0 - these rows have no useful information
nrow(DWRMeHg_new) #Number rows before
## [1] 675
#CODE BELOW REQUIRES USER TROUBLESHOOTING DEPENDING ON AVAILABLE COLUMNS AND SPREADSHEET SPECIFIC CONDITIONS#
DWRMeHg_new <- DWRMeHg_new %>%
  #Set 0 & negative values as blank
  mutate(Result = ifelse(Result <= 0, NA_real_, Result),
         MDL = ifelse(MDL <= 0, NA_real_, MDL),
         RL = ifelse(RL <= 0, NA_real_, RL))
na_results <- DWRMeHg_new %>% #Record rows where Result, MDL, & RL all equal <NA>
  filter( is.na(Result) & is.na(MDL) & is.na(RL) )
nrow(na_results)
## [1] 0
DWRMeHg_new <- anti_join(DWRMeHg_new, na_results, by='SourceRow') #returns rows from DWRMeHg_new not matching values in no_result
nrow(DWRMeHg_new) #Number rows after
## [1] 675
  # Format Units Column - "ng/L", "mg/Kg"
unique(DWRMeHg_new$Unit) #Identifies OLDNAMES
## [1] "ng/L"
DWRMeHg_new <- DWRMeHg_new %>%
  standardizeUnits
unique(DWRMeHg_new$Unit)
## [1] "ng/L"
  # Format Date and Time Column #
# NEED TO TALK ABOUT HOW WE WANT TO DO THIS - To graph in R we need Date and Time in same column
# THE EXAMPLE CODE BELOW ASSUMES DATE AND TIME ARE IN SEPERATE COLUMNS
#date and time already in same column 
DWRMeHg_new <- DWRMeHg_new %>%
  mutate(
    #FORMAT SampleDateTime COLUMN TO DATE FORMAT
    SampleDateTime = SampleDate,     #SampleDate is already in Date & Time format
    SampleDate = format(lubridate::ymd_hms(SampleDateTime), "%Y-%m-%d"),
    SampleTime = format(lubridate::ymd_hms(SampleDateTime), "%H:%M:%S")
  )

#View(DWRMeHg_new)

## SAVE FORMATTED DATA AS EXCEL FILE ##
writexl::write_xlsx(DWRMeHg_new, path='Reeval_Impl_Goals_Linkage_Analysis/Data/Aqueous/DWRMeHg_ceden_format.xlsx')
# In excel, to convert SampleDate column to Date format
# 1 - Select the date column.
# 2 - Go to the Data-tab and choose "Text to Columns".
# 3 - On the first screen, leave radio button on "delimited" and click Next.
# 4 - Unselect any delimiter boxes (everything blank) and click Next.
# 5 - Under column data format choose Date, select YMD
# 6 - Click Finish.

The R session information (including the OS info, R version and all packages used):

    sessionInfo()
## R version 4.2.2 (2022-10-31 ucrt)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 22621)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=English_United States.utf8  LC_CTYPE=C                            
## [3] LC_MONETARY=English_United States.utf8 LC_NUMERIC=C                          
## [5] LC_TIME=English_United States.utf8    
## system code page: 65001
## 
## attached base packages:
## [1] grid      stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] mgcv_1.8-41        nlme_3.1-160       lubridate_1.8.0    plotly_4.10.0     
##  [5] readxl_1.4.1       actuar_3.3-0       NADA_1.6-1.1       forcats_0.5.2     
##  [9] stringr_1.4.1      dplyr_1.0.9        purrr_0.3.4        readr_2.1.2       
## [13] tidyr_1.2.0        tibble_3.1.8       ggplot2_3.3.6      tidyverse_1.3.2   
## [17] fitdistrplus_1.1-8 survival_3.4-0     MASS_7.3-58.1     
## 
## loaded via a namespace (and not attached):
##  [1] httr_1.4.4          jsonlite_1.8.0      viridisLite_0.4.1   splines_4.2.2      
##  [5] modelr_0.1.9        assertthat_0.2.1    highr_0.9           googlesheets4_1.0.1
##  [9] cellranger_1.1.0    yaml_2.3.5          pillar_1.8.1        backports_1.4.1    
## [13] lattice_0.20-45     glue_1.6.2          digest_0.6.29       rvest_1.0.3        
## [17] colorspace_2.0-3    htmltools_0.5.3     Matrix_1.5-1        pkgconfig_2.0.3    
## [21] broom_1.0.1         haven_2.5.1         webshot_0.5.3       scales_1.2.1       
## [25] tzdb_0.3.0          googledrive_2.0.0   generics_0.1.3      ellipsis_0.3.2     
## [29] withr_2.5.0         lazyeval_0.2.2      cli_3.3.0           magrittr_2.0.3     
## [33] crayon_1.5.1        evaluate_0.16       fs_1.5.2            fansi_1.0.3        
## [37] xml2_1.3.3          tools_4.2.2         data.table_1.14.2   hms_1.1.2          
## [41] expint_0.1-7        gargle_1.2.0        lifecycle_1.0.1     munsell_0.5.0      
## [45] reprex_2.0.2        writexl_1.4.0       compiler_4.2.2      rlang_1.0.5        
## [49] rstudioapi_0.14     htmlwidgets_1.5.4   crosstalk_1.2.0     rmarkdown_2.16     
## [53] gtable_0.3.1        DBI_1.1.3           R6_2.5.1            knitr_1.40         
## [57] fastmap_1.1.0       utf8_1.2.2          stringi_1.7.8       vctrs_0.4.1        
## [61] dbplyr_2.2.1        tidyselect_1.1.2    xfun_0.32
    Sys.time()
## [1] "2023-12-29 15:24:47 PST"