library(acs)
library(leaflet)
library(rgdal)
library(RColorBrewer)
library(leaflet)
library(sf)
library(ROCR)
library(mapview)
library(tigris)
library(sp)
library(ggplot2)
library(dplyr)
library(tigris)
library(tigris)
options(tigris_class = "sf")
options(tigris_use_cache=TRUE)
mydata<-zctas(cb=F, year=2015)

## Use library(tigris) to get the ZIPCODES in the US (seee the the blow code to calculate mydata)

mydata<-zctas(cb=F, year=2015)

#dfw <- tracts(state = 'TX', county = c('Dallas', 'Tarrant'))
#bexar<- tracts(state = 'TX', county = c('Bexar'))

# Texas zip code data
zip <- read.csv("~/Google Drive/TigrisShapeFiles/TxEstablishments_Employees.csv",stringsAsFactors = F)
tx <- dplyr::filter(zip, STATE == "TX")


# Get polygon data for TX onlyZCTA5CE10
txzips<-unique(tx$ZIP)
#mypoly <- subset(mydata, ZCTA5CE10 %in% txzips)
tx$zip<-as.character(tx$ZIP)

mdat<-geo_join(mydata, tx, by_sp="ZCTA5CE10", by_df="zip",how="inner")

#bexar_merged<-st_join(mdat,bexar)

#plot(mdat["ZCTA5CE10"])
pf<-mdat%>%mutate(ests=as.numeric(Establishments), emps=as.numeric(Employees))
mapview(pf["Establishments"])
mapview(pf["Employees"])
brks<-quantile(pf$ests, probs = seq(0,1,length.out =4), na.rm = T)
brke<-quantile(pf$emps, probs = seq(0,1,length.out =4 ), na.rm = T)

pf$quart_est<-cut(pf$ests, brks, include.lowest = T)

pf$quart_emp<-cut(pf$emps, brke, include.lowest = T)


plot_p1<-pf%>%ggplot()+geom_sf(aes(fill=quart_est))+scale_fill_brewer(palette = "Blues", na.value="grey")+ggtitle(label = "Establishments", subtitle = "")+guides(fill=guide_legend(title="Establishments"))


plot_p2<-pf%>%ggplot()+geom_sf(aes(fill=quart_emp))+scale_fill_brewer(palette = "Blues", na.value="grey")+ggtitle(label = "Employees", subtitle = "")+guides(fill=guide_legend(title="Employees"))

plot_p1

plot_p2

pal <- colorQuantile("Blues", NULL, n = 6)

popemp <- paste0("Median household income: ", as.character(pf$Employees))

pal <- colorQuantile("Blues", NULL, n = 6)

popests <- paste0("Median household income: ", as.character(pf$Establishments))


Emp<-leaflet() %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(data =pf, 
              fillColor = ~pal(pf$Employees), 
              fillOpacity = 0.7, 
              weight = 0.2, 
              smoothFactor = 0.2, 
              popup = popemp) %>%
  addLegend(pal = pal, 
            values = pf$Employees, 
            position = "bottomright", 
            title = "Employees in Texas")

Emp
Est<-leaflet() %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(data =pf, 
              fillColor = ~pal(pf$Establishments), 
              fillOpacity = 0.7, 
              weight = 0.2, 
              smoothFactor = 0.2, 
              popup = popests) %>%
  addLegend(pal = pal, 
            values = pf$Employees, 
            position = "bottomright", 
            title = "Establishments in Texas")

Est