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

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


### LOAD DATA ###
#FIND AND REPLACE (Ctrl+F) 'CEDEN' WITH MORE APPROPRIATE NAME (e.g., 'CALFED_data')
#CHANGE 'FILENAME' & 'SHEETNAME' WITH ACTUAL NAMES
CEDENFish <- readxl::read_excel('Reeval_Impl_Goals_Linkage_Analysis/Data/Fish/CEDENFish.xlsx', sheet='ceden_data_20181024083944', guess_max = 30000)
nrow(CEDENFish) #number of rows should match the Excel file (minus the header row)
## [1] 9948
#Load CEDEN StationCodes to look up CoordSystem by StationCode
CedenCoordSys <- readxl::read_excel('Reeval_Impl_Goals_Linkage_Analysis/Data/Fish/0_CEDEN_StationCode_CoordSystem lookup.xlsx', sheet='Worksheet', guess_max = 30000)
CedenCoordSys <- CedenCoordSys %>%
  select(StationCode, Datum) %>%
  rename('CoordSystem' = 'Datum')


### 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','CompositeProgramName','CompositeParentProjectName','CompositeProjectCode','CompositeProjectName','CompositeCompositeID',
               'CompositeStationName','CompositeStationCode','CompositeTargetLatitude','CompositeTargetLongitude','CompositeSampleDate','CompositeCommonName',
               'CompositeFinalID','NumberFishPerComp','CompositeTissueName','Method','Analyte','Unit','Result','ResQualCode','MDL','RL','WeightAvg g','TLMin mm',
               'TLMax mm','TLAvgLength mm','CompositeRowID','SampleID','SWRCBWatTypeCode','QACode','BatchVerification','ComplianceCode','ResultComments','LabSubmissionCode'
)

#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)

CEDENFish_new <- CEDENFish %>%
  select(keep_cols) %>% #DO NOT CHANGE - selects columns specified above
  rename(
    #Rename CEDEN columns to CEDEN format here: CEDEN 'COLUMNNAME' = CEDENFish 'COLUMNNAME'
    #DELTE COLUMN NAMES THAT DO NOT HAVE AN EQUIVALENT COLUMN IN THE CEDEN
    'ProgramName' = 'CompositeProgramName',
    'ParentProjectName' = 'CompositeParentProjectName',
    'ProjectCode' = 'CompositeProjectCode',
    'ProjectName' = 'CompositeProjectName',
    'CompositeID' = 'CompositeCompositeID',
    'ResultQualCode' = 'ResQualCode',
    'StationName' = 'CompositeStationName',
    'StationCode' = 'CompositeStationCode',
    'TargetLatitude' = 'CompositeTargetLatitude',
    'TargetLongitude' = 'CompositeTargetLongitude',
    'SampleDate' = 'CompositeSampleDate',
    'CommonName' = 'CompositeCommonName',
    'TaxonomicName' = 'CompositeFinalID',
    'TissueName' = 'CompositeTissueName',
    'WBT' = 'SWRCBWatTypeCode'
  ) %>%
  mutate(
    #Create Missing column or modify existing column here: CEDEN COLUMNNAME = 'SPECIFIED VALUE' or FUNCTION
    #DELETE COLUMN NAMES THAT DO NOT NEED TO BE CHANGED
    CitationCode = 'CEDENFish',
    SampleTime = NA_character_
  ) %>%
  left_join(
    ., CedenCoordSys, by='StationCode' #adds in CoordSystem column
  )

nrow(CEDENFish_new)
## [1] 9948
#str(CEDENFish_new) #just to check data class of different columns - e.g., is Date column in POSIX format?
#View(CEDENFish_new)


### FORMAT COLUMN PARAMETERS ###

  # Standardize WBT (WaterBodyType) Groups - "River/Stream", "Estuary", "Drain/Canal", "Wetland", "Spring", "Slough", 
  #                                          "Pond",  "Lake/Reservoir", "Delta", "Forebay/Afterbay", "Not Recorded" #
unique(CEDENFish_new$WBT) #Identifies OLDNAMES
##  [1] "R_O"  "R_Un" "W_T"  "L_F"  "R"    "B"    "R_W"  "E"    "W_F"  "L_Un"
#STANDARD CODE TO CHANGE GROUPING NAMES
CEDENFish_new <- CEDENFish_new %>%
  mutate(WBT = recode(WBT,
                      "B" = "Bay",
                      "E" = "Estuary",
                      "L_F" = "Lake/Reservoir",
                      "L_Un" = "Lake/Reservoir",
                      "R" = "River/Stream",
                      "R_O" = "River/Stream",
                      "R_Un" = "River/Stream",
                      "R_W" = "River/Stream",
                      "W_F" = "Wetland, Fresh",
                      "W_T" = "Wetland, Tidal")
  )
unique(CEDENFish_new$WBT) #New naming structure for WBT Groupings
## [1] "River/Stream"   "Wetland, Tidal" "Lake/Reservoir" "Bay"            "Estuary"       
## [6] "Wetland, Fresh"
# Filter by WBT
CEDENFish_new <- CEDENFish_new %>%
  filter(WBT != "Bay") # ony remove WBTs that are Bay - we want to keep the 6 lake/reservoir sites
unique(CEDENFish_new$WBT)
## [1] "River/Stream"   "Wetland, Tidal" "Lake/Reservoir" "Estuary"        "Wetland, Fresh"
nrow(CEDENFish_new)
## [1] 9869
  # Standardize TissueName Groups - "Fillet" & "Whole Body" #
unique(CEDENFish_new$TissueName)
## [1] "whole organism"            "whole without tail"        "tail (tail of crustacean)"
## [4] "fillet"                    "liver"                     "whole without gut"        
## [7] "soft tissue"
CEDENFish_new <- CEDENFish_new %>%
  filter(TissueName %in% c('whole organism', 'fillet')) %>% # other "whole" variations where for clams or shellfish
  mutate(TissueName = recode(TissueName,
                             'fillet' = 'Fillet',
                             'whole organism' = 'Whole Body'))
unique(CEDENFish_new$TissueName)
## [1] "Whole Body" "Fillet"
  # Standardize Analyte Groups - "Mercury, Total" (we consider Total Mercury and Methylmercury to be approx equal) #
unique(CEDENFish_new$Analyte)
## [1] "Mercury, Methyl, Total" "Mercury, Total"
CEDENFish_new <- CEDENFish_new %>%
  mutate( Analyte = recode(Analyte, "Mercury, Methyl, Total" = "Mercury, Total") )
#Create 'Analyte' column from Analyte & Analyte_part2 columns - then delete Analyte_part2 column##
unique(CEDENFish_new$Analyte) #New naming structure for Analyte Groupings
## [1] "Mercury, Total"
  # Format Result Column to Numeric#
  # Check column for text - based on text user needs to decide what to do
if(!is.numeric(CEDENFish_new$Result)){
  old <-CEDENFish_new$Result
  new <-CEDENFish_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)),
             ".\nACTIONS TAKEN:\n",
             "~explain here~.\n"))
  #CEDENFish_new <- CEDENFish_new %>%
  #  mutate( #Due stuff to prep column to be converted to Numeric
  #    Result = as.numeric(new)
  #    )
} else {
  cat("'Result' column is in numeric format\n")
  CEDENFish_new <- CEDENFish_new %>%
    mutate( Result = if_else(Result == 0, NA_real_, Result) ) #Convert 0 values to blanks
  }
## 'Result' column is in numeric format
  # Format MDL Column to Numeric#
  # Check column for text - based on text user needs to decide what to do
if(!is.numeric(CEDENFish_new$MDL)){
  old <-CEDENFish_new$MDL
  new <-CEDENFish_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"))
  #CEDENFish_new <- CEDENFish_new %>%
  #  mutate( #Due stuff to prep column to be converted to Numeric
  #    MDL = as.numeric(new)
  #  )
} else {
  cat("'MDL' column is in numeric format\n")
  }
## '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(CEDENFish_new$RL)){
  old <-CEDENFish_new$RL
  new <-CEDENFish_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"))
  #CEDENFish_new <- CEDENFish_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
# Standardize ResultQualCode Groups - "ND", "DNQ", NA#
unique(CEDENFish_new$ResultQualCode) #Identifies OLDNAMES
## [1] "="   "ND"  "NR"  "NA"  "DNQ"
CEDENFish_new <- CEDENFish_new %>%
  mutate(ResultQualCode = recode(ResultQualCode,
                              "NR" = "ND", #Based on investigation of dataset, NR do not have a Result value and we determined that NR could be interpreted as a ND
                              "NA" = "ND"))  #Based on investigation of dataset, NA do not have a Result value and we determined that NA could be interpreted as a ND - only one sample was an NA
unique(CEDENFish_new$ResultQualCode) #New naming structure for ResultQualCode Groupings
## [1] "="   "ND"  "DNQ"
  # Format Units Column - "mg/Kg ww" or "mg/Kg dw"
unique(CEDENFish_new$Unit) #Identifies OLDNAMES
## [1] "ug/g dw" "ug/g ww" "NR dw"   "NR ww"   "ug/g nr"
CEDENFish_new <- CEDENFish_new %>%
  filter(Unit != 'ug/g nr') %>% #Determined that the 2 samples with these units are actually in a reservoir not part of rivers or in delta
  mutate(
    #NR dw & NR ww Units line up with NR & NA ResultQualCODE, which were determined to be NDs (changed above) - so change units to match ug/g
    Unit = recode(Unit,
                  'NR dw' = 'ug/g dw',
                  'NR ww' = 'ug/g ww')) %>%
  standardizeUnits(pp = "mass")
unique(CEDENFish_new$Unit) #New naming structure for Unit Groupings
## [1] "mg/Kg dw" "mg/Kg ww"
  # Check if Result, MDL, & RL Columns all equal <NA> or 0 - these rows have no useful information
nrow(CEDENFish_new) #Number rows before
## [1] 8414
#CODE BELOW REQUIRES USER TROUBLESHOOTING DEPENDING ON AVAILABLE COLUMNS AND SPREADSHEET SPECIFIC CONDITIONS#
CEDENFish_new <- CEDENFish_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 <- CEDENFish_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
CEDENFish_new <- anti_join(CEDENFish_new, na_results, by='SourceRow') #returns rows from CEDENFish_new not matching values in no_result
nrow(CEDENFish_new) #Number rows after
## [1] 8414
  # Format Date and Time Column #
# THE EXAMPLE CODE BELOW ASSUMES DATE AND TIME ARE IN SAME COLUMNS - IF TIME IS IN SEPERATE COLUMN LOOK AT AQ LINKAGE DATA TEMPLATE
CEDENFish_new <- CEDENFish_new %>%
  #rowise() %>%    # rowise is very slow - so used sapply to make this a rowise operation
  mutate(
    #If SampleDate & CollectioTIme are not in Character format by defualt, turn it into a character class so it exports better
    SampleDate = ifelse(sapply(SampleDate, is.character), SampleDate, as.character(as.Date(SampleDate))),
    SampleTime = ifelse(sapply(SampleTime, is.character), SampleTime, format(lubridate::ymd_hms(SampleTime), "%H:%M:%S")),
    #COMBINE DATE AND TIME INTO SampleDateTime COLUMN
    SampleDateTime = ifelse(!is.na(SampleTime), paste(SampleDate, SampleTime), paste(SampleDate, '00:00:00')),
    #FORMAT SampleDateTime COLUMN TO DATE FORMAT
    SampleDateTime = lubridate::ymd_hms(SampleDateTime)
  )


### REMOVE TEMPORARY COLUMNS ###
#CEDENFish_new <- CEDENFish_new %>%
#  select(-one_of(temp_cols)) #Remove temp columns since they are no longer needed
#View(CEDENFish_new)

## SAVE FORMATTED DATA AS EXCEL FILE ##
writexl::write_xlsx(CEDENFish_new, path='Reeval_Impl_Goals_Linkage_Analysis/Data/Fish/CEDENFish_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=English_United States.utf8   
## [3] LC_MONETARY=English_United States.utf8 LC_NUMERIC=C                          
## [5] LC_TIME=English_United States.utf8    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] lubridate_1.8.0    plotly_4.10.0      readxl_1.4.1       actuar_3.3-0      
##  [5] NADA_1.6-1.1       forcats_0.5.2      stringr_1.4.1      dplyr_1.0.9       
##  [9] purrr_0.3.4        readr_2.1.2        tidyr_1.2.0        tibble_3.1.8      
## [13] ggplot2_3.3.6      tidyverse_1.3.2    fitdistrplus_1.1-8 survival_3.4-0    
## [17] MASS_7.3-58.1     
## 
## loaded via a namespace (and not attached):
##  [1] lattice_0.20-45     assertthat_0.2.1    digest_0.6.29       utf8_1.2.2         
##  [5] R6_2.5.1            cellranger_1.1.0    backports_1.4.1     reprex_2.0.2       
##  [9] evaluate_0.16       highr_0.9           httr_1.4.4          pillar_1.8.1       
## [13] rlang_1.0.5         lazyeval_0.2.2      googlesheets4_1.0.1 rstudioapi_0.14    
## [17] data.table_1.14.2   Matrix_1.5-1        splines_4.2.2       googledrive_2.0.0  
## [21] htmlwidgets_1.5.4   munsell_0.5.0       broom_1.0.1         compiler_4.2.2     
## [25] modelr_0.1.9        xfun_0.32           pkgconfig_2.0.3     htmltools_0.5.3    
## [29] tidyselect_1.1.2    fansi_1.0.3         viridisLite_0.4.1   crayon_1.5.1       
## [33] tzdb_0.3.0          dbplyr_2.2.1        withr_2.5.0         grid_4.2.2         
## [37] jsonlite_1.8.0      gtable_0.3.1        lifecycle_1.0.1     DBI_1.1.3          
## [41] magrittr_2.0.3      scales_1.2.1        writexl_1.4.0       cli_3.3.0          
## [45] stringi_1.7.8       fs_1.5.2            xml2_1.3.3          ellipsis_0.3.2     
## [49] generics_0.1.3      vctrs_0.4.1         expint_0.1-7        tools_4.2.2        
## [53] glue_1.6.2          hms_1.1.2           fastmap_1.1.0       colorspace_2.0-3   
## [57] gargle_1.2.0        rvest_1.0.3         knitr_1.40          haven_2.5.1
    Sys.time()
## [1] "2024-01-05 09:40:34 PST"