load libraries

library(shiny)
library(rgdal)
library(leaflet)
library(plyr)
library(stringr)
library(RColorBrewer)
library(stringr)
library(dplyr)

load PUR data

#PUR <- read.csv(paste("./2012/udc12_01.txt", sep=""), stringsAsFactors=FALSE)
load("./data/2012/PUR-data.Rda")
names(PUR)
##  [1] "use_no"       "prodno"       "chem_code"    "prodchem_pct"
##  [5] "lbs_chm_used" "lbs_prd_used" "amt_prd_used" "unit_of_meas"
##  [9] "acre_planted" "unit_planted" "acre_treated" "unit_treated"
## [13] "applic_cnt"   "applic_dt"    "applic_time"  "county_cd"   
## [17] "base_ln_mer"  "township"     "tship_dir"    "range"       
## [21] "range_dir"    "section"      "site_loc_id"  "grower_id"   
## [25] "license_no"   "planting_seq" "aer_gnd_ind"  "site_code"   
## [29] "qualify_cd"   "batch_no"     "document_no"  "summary_cd"  
## [33] "record_id"    "comtrs"       "error_flag"

Clean PUR Data, add MTRS file

#fix MTRS field by adding preceding zeros
PUR$range <- str_pad(PUR$range, 2, pad = "0")
PUR$township <- str_pad(PUR$township, 2, pad = "0")
PUR$section <- str_pad(PUR$section, 2, pad = "0")

#Create MTRS Field
PUR$MTRS <- paste(PUR$base_ln_mer, PUR$township, PUR$tship_dir, PUR$range, PUR$range_dir, PUR$section, sep="")
head(PUR$MTRS)
## [1] "M03S03E17" "M03S01E24" "M03S02E25" "M03S02E21" "M03S02E29" "M03S02E14"
#replace NA with 0 for acres and pounds
PUR[is.na(PUR[,"lbs_chm_used"]),"lbs_chm_used"] <- 0
PUR[is.na(PUR[,"acre_treated"]),"acre_treated"] <- 0

load PLSS shapefiles

#load county shapefiles
allCounties <- readOGR("./data/shapefiles/counties/", layer="cb_2014_us_county_20m")
CaCounties <- subset(allCounties, allCounties@data$STATEFP=="06")

#load PLSS MTRS data
PLSS <- readOGR("./data/shapefiles/plss/", layer="mtrs")
#map counties
leaflet() %>% addProviderTiles("CartoDB.Positron") %>%
  addPolygons(data=CaCounties, weight=2, fill="#eaeca3", color="#000")

#map sample data, from Fresno County
leaflet() %>% addProviderTiles("CartoDB.Positron") %>%
  addPolygons(data=subset(PLSS,PLSS@data$COUNTY_CD==10),
              weight=1, fill="#eaeca3", color="#000")

Map all pesticide use in 2012, aggregated by county

#summarize PUR data for each county
county.sum <- ddply(PUR, ~county_cd, summarise, pounds=sum(lbs_chm_used), acres=sum(acre_treated))
county.sum$county_cd <-  str_pad(county.sum$county_cd, 3, pad = "0")

#add county names
county.name <- read.csv("./data/2012/county.txt", col.names =c("county_cd","county_name"))
county.name$county_cd <-  str_pad(county.name$county_cd, 3, pad = "0")
county.sum <- merge(county.sum, county.name)
#function for Proper Capitalization
Proper <- function(x) gsub("(?<=\\b)([a-z])", "\\U\\1", tolower(x), perl=TRUE)
#properly capitalize county name
county.sum$county_name <- Proper(as.character(county.sum$county_name))

#load spatial data and merge with county-level pesticide data
mapData <- CaCounties
mapData@data = data.frame(mapData@data, county.sum[match(mapData@data[,"NAME"], county.sum[,"county_name"]),])

#set color palettes
bins.quantile <- quantile(mapData@data[,"pounds"], c(0, .20, .40, .60, .80, .95, 1), na.rm = TRUE) 
colorPal <- colorBin("YlOrRd", mapData@data[,"pounds"], bins=bins.quantile)

#map all pesticide use by county
 leaflet() %>%
   addProviderTiles("CartoDB.Positron") %>%
   setView(-122.4434463, 37.758238, zoom = 6) %>%
   addPolygons(data = mapData,
               color="#000000",
               weight=1,
               fillColor=~colorPal(mapData@data[,"pounds"]),
               popup=~paste("<strong>Acres Treated:</strong>:",round(acres),"<br>",
                            "<strong>Pounds Applied:</strong>:",round(pounds))
               ) %>%
   addLegend(title = paste("Total Pounds of Pesticides<br> per County in 2012"), pal = colorPal, values = mapData@data[,"pounds"],
             opacity = 0.9, position="bottomleft",
             labFormat = labelFormat(transform = function(x) round(x))
             )