Can't run codes because the dataset can't be found

shiny
rstudio

#1

Hi everyone. I am currently facing an issue with my rshiny codes. I am trying to run to the set of codes below, but everytime I run it directly in rshiny, it mentions that a couple of Datasets can't be found eg. Error in : Dataset res_combined not found. But, when I run my codes first in the r markdown page before running these codes again, it works! I think it's because I have already loaded in the datasets necessary for the rshiny application to work, through the rmarkdown page. So, I think the problem is because I haven't uploaded the datasets in rshiny, even though I have assigned the datasets to variable for rshiny to use. Could anyone assist me with this matter?

library(shiny)
library(shinythemes)
library(readr)
library(ggplot2)
library(stringr)
library(dplyr)
library(DT)
library(tools)
library(leaflet)
library(tmap)
library(sf)
library(tidyverse)
library(ggmap)
library(classInt)
library(RColorBrewer)
library(rgdal)
library(SpatialAcc)
library(GISTools)
library(rgeos)
library(REAT)
library(plotly)
library(rsconnect)

residential <- read_csv("AttributeTables/sgSelectedBuildingsV7.csv")
bus_stops <- read_csv("AttributeTables/bus_stopsv4.csv")
residential_asc <- residential[with(residential, order(SUBZONE_N)),]
bus_stops_asc <- bus_stops[with(bus_stops, order(SUBZONE_N)),]
hawker_centres <- read_csv("AttributeTables/CombinedHawkerCentreLocationsV4.csv")
options(shiny.maxRequestSize=30*1024^2)

ui <- fluidPage(theme = shinytheme("simplex"),

titlePanel("HawkerLeh", windowTitle = "HawkerLeh"),

sidebarLayout(

 sidebarPanel(
   
   h4("File Upload"),
   
   fileInput("file1", "Choose file for upload (CSV, XLS Files Only)",
             multiple = TRUE,
             accept = c("text/csv",
                        "text/comma-separated-values,text/plain")),
   
   
   h4("Plotting"),
   
   selectInput(inputId = "hawker_type", 
               label = "Hawker Type:",
               choices = c("Food Junction" = "Food Junction", 
                           "Kopitiam" = "Kopitiam", 
                           "Koufu" = "Koufu", 
                           "NEA" = "NEA",
                           "All" = "all"), 
               selected = "all"), 
   
   radioButtons(inputId = "analysis",
                label = "Breakdown By: ",
                choices = c("Residential" = "residential",
                            "Bus Stops" = "busstops")
                ),
   
   br(),
   
   conditionalPanel(
     
     condition = "input.analysis == 'residential'",
     
     radioButtons(inputId = "hansen",
                  label = "Hansen Accessibility by: ",
                  choices = c("REAT" = "reat",
                              "Spatial Acc" = "spacc")
     ),         
     
     selectInput(inputId = "residential_subzone", 
                 label = "Subzone:",
                 choices = unique(residential_asc[,7])
     ),
       
     conditionalPanel(
       condition = "input.hansen == 'reat'",
       
       sliderInput(inputId = "radius", 
                   label = "Radius", 
                   min = 100, max = 1000, value = 100)
     )
       
  ),
   
 conditionalPanel(
   condition = "input.analysis == 'busstops'",
   
   selectInput(inputId = "bus_stops_subzone", 
               label = "Subzone:",
               choices = unique(bus_stops_asc[,8])
   ),
     
   sliderInput(inputId = "bus_radius", 
               label = "Buffer Radius: ", 
               min = 100, max = 1000, value = 100)
   
 )
 
),

 mainPanel(
   
   tabsetPanel(id = "tabspanel", type = "tabs",
               tabPanel(title = "Plot", 
                        leafletOutput(outputId = "final"),
                        br()
                        ),
               tabPanel(title = "Data", 
                        br(),
                        DT::dataTableOutput(outputId = "datatable")),
               tabPanel("CSV Upload",
                        br(),
                        DT::dataTableOutput("contents"))
               
   )
 )   

)
)

server <- function(input, output, session) {

hawker_centres_subset <- reactive({
req(input$hawker_type)
if(input$hawker_type == "all"){
filter(hawker_centres)
} else {
filter(hawker_centres, POI_TYPE == input$hawker_type)
}
})

residential_subset <- reactive({
req(input$residential_subzone)
filter(residential, SUBZONE_N == input$residential_subzone)
})

bus_stops_subset <- reactive({
req(input$bus_stops_subzone)
filter(bus_stops, SUBZONE_N == input$bus_stops_subzone)
})

output$final <- renderLeaflet({

finalMap <- NULL
if(input$analysis == "busstops"){
  
  bus_stops <- bus_stops_subset()
  hawker_centres <- hawker_centres_subset()
  distance_filter <- 10 * input$bus_radius
  distance_bs <- dist.mat(bus_stops, "BUS_STOP_N", "Y_ADDR", "X_ADDR",
                          hawker_centres, "NAME", "Y_ADDR", "X_ADDR", unit = "km")
  x <- transform(distance_bs, distance = as.numeric(distance_bs$distance * 1000))
  distance_bs <- x
  distance_bs <- distance_bs %>% filter(distance <= distance_filter)
  **_bs_combined_** <- left_join(distance_bs, hawker_centres, c("to" = "NAME"))

  hansen_bs <- hansen(bs_combined, "from", "to", "SEATING_CAP", "distance", gamma = 1,
                   lambda = -2, atype = "pow", dtype = "pow")

  hansen_bs$from <- NULL
  hansen_reat_bs <- data.frame(bus_stops[,c(1,3,4,5)],hansen_bs)

  colPal <- colorNumeric(
    palette = "Blues",
    domain = hansen_reat_bs$accessibility
  )

  bs_map = leaflet(hansen_reat_bs) %>% addTiles() %>% addCircles(lng = ~X_ADDR, lat = ~Y_ADDR, weight = 1, radius = ~sqrt(accessibility) * 500, color = ~colPal(accessibility), opacity = 1, fill = TRUE, fillColor = ~colPal(accessibility), fillOpacity = 0.6) %>%
    addMarkers(lng = ~X_ADDR, lat = ~Y_ADDR, options = markerOptions(clickable = TRUE, title = paste("Name:", hansen_reat_bs$LOC_DESC, "Accessibility:", hansen_reat_bs$accessibility), riseOnHover = TRUE, opacity = 0.7)) %>%
    addCircles(data = bs_combined, lng = ~X_ADDR, lat = ~Y_ADDR, weight = 1, radius = ~sqrt(SEATING_CAP), color = "green", fill = TRUE, fillColor = "green", fillOpacity = 1) %>%
    addCircleMarkers(data = bs_combined, lng = ~X_ADDR, lat = ~Y_ADDR, weight = 1, opacity = 0.6, color = "green", popup = paste("Name:", bs_combined$to, "<br>", "Seating capacity:", bs_combined$SEATING_CAP, "<br>", "Type:", bs_combined$POI_TYPE, "<br>")) %>%
    addLegend(position = "bottomleft", pal = colPal, bins = 4, title = "Accessibility", values = hansen_reat_bs$accessibility)

  finalMap = bs_map
  
} 

if(input$analysis == "residential" && input$hansen == "reat"){
  
  hawker_centres <- hawker_centres_subset()
  residential <- residential_subset()

  distance_filter <- 10 * input$res_radius
  distance_res <- dist.mat(residential, "OSM_ID", "Y_ADDR", "X_ADDR",
                           hawker_centres, "NAME", "Y_ADDR", "X_ADDR", unit = "km")
  x <- transform(distance_res, distance = as.numeric(distance_res$distance * 1000))
  distance_res <- x
  res_combined <- left_join(distance_res, hawker_centres, c("to"="NAME"))

  hansen_res <- hansen(res_combined, "from", "to", "SEATING_CAP", "distance",
                       gamma = 1, lambda = -2, atype = "pow", dtype = "pow")
  hansen_res$from <- NULL
  hansen_reat_res <- data.frame(residential[,c(1,3,4,5)],hansen_res)

  colPal <- colorNumeric(
    palette = "Blues",
    domain = hansen_reat_res$accessibility
  )

  map_reat_res = leaflet(hansen_reat_res) %>% addTiles() %>%
    addCircles(lng = ~X_ADDR, lat = ~Y_ADDR, weight = 1, radius = ~sqrt(hansen_reat_res$accessibility) * 1000, color = ~colPal(accessibility), opacity = 1, fill = TRUE, fillColor = ~colPal(accessibility), fillOpacity = 0.6) %>%
    addMarkers(lng = ~X_ADDR, lat = ~Y_ADDR, options = markerOptions(clickable = TRUE, title = paste("Residential type:", hansen_reat_res$TYPE, ", ", "Accessibility:", hansen_reat_res$accessibility), riseOnHover = TRUE, opacity = 0.7)) %>%
    addCircles(data = res_combined, lng = ~X_ADDR, lat = ~Y_ADDR, weight = 1, radius = 10, color = "green", fill = TRUE, fillColor = "green", fillOpacity = 1) %>%
    addCircleMarkers(data = res_combined, lng = ~X_ADDR, lat = ~Y_ADDR, weight = 1, color = "green",
                     popup = paste("Name:", res_combined$to, "<br>", "Seating capacity:", res_combined$SEATING_CAP, "<br>", "Type:", res_combined$POI_TYPE, "<br>")) %>%
    addLegend(position = "bottomleft", pal = colPal, bins = 4, title = "Accessibility", values = hansen_reat_res$accessibility)

  finalMap = map_reat_res
  
}    

finalMap

})
}

Run the application

shinyApp(ui = ui, server = server)