I am struggling to create my first shiny app. I am trying to see if I can map data reported by the USDA using their API within shiny environment- using leaflet. I tried to follow an example I found in R Studio Community ~shiny-leaflet-map-filtering-by-years-in-different-columns/1287.
Could you please let me know where the error might have happened? Thanks!
global.r File
## Install and Load Appropriate Packages ##
list.of.packages <- c('tidyr', 'shiny', 'ggplot2', 'RCurl', 'plyr', 'reshape', 'dplyr', 'geojsonio', 'rgdal', "leaflet", "RColorBrewer")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
apikey <- "988F7E5A-149B-301F-AF3B-905928EAA13A"
library(leaflet)
library(RColorBrewer)
library(httr)
library(plyr)
library(RCurl)
library(geojsonio)
library(rgdal)
library(shiny)
source("keys.R")
crops <- c("CORN", "WHEAT", "SOYBEANS")
harvest_parameter <- c("CORN, GRAIN - ACRES HARVESTED", "WHEAT - ACRES HARVESTED", "SOYBEANS - ACRES HARVESTED")
fNames <- c("NASS_CORN_DATA", "NASS_WHEAT_DATA", "NASS_SOYBEANS_DATA")
df_request <- data.frame(crops, harvest_parameter, fNames)
dataDir <- "Data"
for (row in 1:nrow(df_request)) {
crop <- df_request[row, "crops"]
hp <- df_request[row, "harvest_parameter"]
eachFile <- df_request[row, "fNames"]
destFile <- paste0("\\.", crop, "*|csv")
# Check if the file exists
if (!file.exists(paste0(dataDir,"/", eachFile,".csv"))) {
## Get data for each crop
cat(paste0("\n\n\nDownloading Data for :", crop," \n\n"))
#each_crop <- paste(crop,"api.url4acres")
cropapi.url4acres <- paste0(
'http://quickstats.nass.usda.gov/api/api_GET/?key=',
apikey,
'&source_desc=SURVEY',
'&agg_level_desc=STATE',
'&commodity_desc=',
crop,
'&reference_period_desc=YEAR',
'&year__GE=2000',
'&short_desc=',
hp,
sep = ''
)
### API Get using request parameters
cropapi.url4acres <- GET(cropapi.url4acres)
### Convert from JSON to text
crop_data <-
fromJSON(content(cropapi.url4acres, "text"))$data
ifelse(!dir.exists(file.path("Data")), dir.create(file.path("Data")), FALSE)
write.csv(crop_data, file = paste0("./Data/", paste0(eachFile, ".csv")))
}
else{
cat(paste0("\nData already exists for :", crop))
}
}
# Function to convert acres into hectares
in_to_ha <- function(data_in_acres) {
value_hectare <- data_in_acres * 0.404686
return(value_hectare)
}
# Read the data
all_crop_production_files <- list.files("Data",
pattern = "*.csv",
full.names = TRUE)
# Reading all the CSV files at onceinstead of a loop, cool beans!
all_crop_production_data <- do.call(rbind, lapply(all_crop_production_files, read.csv))
keepColumns <- c("state_name", "state_alpha", "Value", "state_ansi","commodity_desc","year")
reducedCropProductionData <- all_crop_production_data[, keepColumns]
# For some reason, the data is stored as factpr, conver it to numeric
reducedCropProductionData[,'Value'] <- as.numeric(reducedCropProductionData[,'Value'])
# Convert the values in hectare
reducedCropProductionData$Value_ha <- sapply(reducedCropProductionData$Value, in_to_ha)
# Write the csv file in output directory
write.csv(reducedCropProductionData, file = paste0(dataDir,"/", "CleanData.txt"))
# Read the json file
# Geo json file obtained from http://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_outline_20m.json
states <- geojsonio::geojson_read("./Data/gz_2010_us_040_00_20m.json",what = "sp")
# Convert State Name to Proper Case
capFirst <- function(s) {
paste(toupper(substring(s, 1, 1)), substring(s, 2), sep = "")
}
reducedCropProductionData$state_name <- capFirst(reducedCropProductionData$state_name)
reducedCropProductionDataSp <- merge(states, reducedCropProductionData, by.x = "NAME", by.y = "state_name")
ui.R File:
###### ui.R
# Create User Interface
ui <- fluidPage(
titlePanel("Crop Production Area (in Ha.) in the United States"),
helpText(
"Create crop production acreage map from
information from the NASS Quick Stats."
),
sidebarLayout(
sidebarPanel(
h3(" Select Crop"),
selectInput(
"CropInput",
label = "Select a crop to display",
choices = c("Corn", "Soybean", "Wheat"),
selected = "Corn"
)
),
sliderInput(
"sliderYear",
label = "Select Year for Mapping:",
min = 2000,
max = 2017,
value = 2010
)
),
mainPanel(h4(" Map"),
leafletOutput("myMap", height = 800))
)
server.R File:
##### server.R
server <- shinyServer(function(input, output, session) {
updateSelectizeInput(session,
"CropInput",
choices = reducedCropProductionDataSp$commodity_desc,
server = TRUE)
# selected crop
selectedCrop <- reactive({
reducedCropProductionDataSp[reducedCropProductionDataSp$commodity_desc == input$CropInput,]
})
# selected year
selectedYear <- reactive({
switch(input$sliderYear,
reducedCropProductionDataSp$year == input$sliderYear)
})
pal2 <- colorNumeric(palette = "Greens", domain = NULL)
output$Mymap <- renderLeaflet({
leaflet(reducedCropProductionDataSp) %>%
addProviderTiles(providers$Stamen.TonerLite) %>%
setView(lng = -98.583,
lat = 39.833,
zoom = 4) %>%
addPolygons(
data = reducedCropProductionDataSp ,
fillColor = ~ pal2(selectedYear()),
popup = paste0("<strong>State: </strong>",
selectedState()$NAME),
color = "#BDBDC3",
fillOpacity = 0.8,
weight = 1
)
})
})
Run the shiny app
runApp()