Rshiny Crash с функцией карты - PullRequest
0 голосов
/ 05 июня 2019

У меня есть работающее приложение rshiny, но я думаю, что мне нужно добавить некоторые функции, используя реактивные функции, чтобы сделать его более эффективным и предотвратить его падение.Я создал версию приложения, которая использует данные переписи вместо данных, которые я использую, которые являются счетчиками трафика, поэтому я понимаю, что пример несколько тривиален, но я обнаружил, что он ломается, когда выбираются разные состояния в первом фильтре.Здесь я пытаюсь сохранить динамические и каскадные фильтры, где один фильтр информирует последние, которые, кажется, работают нормально, но когда я добавил карту, Rstudio аварийно завершает свою работу без предупреждений.Иногда я могу сделать несколько выборок в первом фильтре без проблем, а затем из ниоткуда бомбить.Я использую Studio v1.1456 и R v3.5.3.

library(shiny)    
library(ggplot2)
library(plotly)
library(dplyr)
library(shinyWidgets)
library(tigris)
library(leaflet)
library(rgeos)
library(mapview)


#install.packages(c("shiny","leaflet","spData","ggplot2","plotly","dplyr","shinyWidgets","rgdal","tigris","readxl","mapviews"))


# Load data
  State_01_Tracts_Sp <- tracts("01")
  State_02_Tracts_Sp <- tracts("02")
  State_04_Tracts_Sp <- tracts("04")
  State_05_Tracts_Sp <- tracts("05")
  State_06_Tracts_Sp <- tracts("06")
  Tracts_Sp <- rbind(State_01_Tracts_Sp ,State_02_Tracts_Sp, State_04_Tracts_Sp, State_05_Tracts_Sp , State_06_Tracts_Sp  )


  #Decode fips into descriptive state and county names
  Tracts_Sp@data$State <- fips_codes$state_name[match(Tracts_Sp@data$STATEFP,fips_codes$state_code)]
  Tracts_Sp@data$County <- fips_codes$county[match(Tracts_Sp@data$COUNTYFP,fips_codes$county_code)]
  #Create a copy of the spatial data's data frame
  Data.. <- Tracts_Sp@data



#Set up User Interface
ui <- fluidPage(
  titlePanel("Census Viewer Test"),
  tabsetPanel(
    #Daily Counts Panel
    ##############
    #Hourly Counts Panel
    #######################
    tabPanel("Tab 1",
             #Call plot 
             fluidRow(column(width = 12,plotlyOutput("county_plot" ))),
             #Location Details 
             fluidRow( 
               column(3,
                      h4("Select Details"),
                      uiOutput("State_selector"),
                      uiOutput("County_selector"),
                      uiOutput("Tract_selector")),
               column(6,
                      #h4("Selected Location"),
                      leafletOutput("map_plot",height = 500))
               #Close row
             )
             #Close panel
    )
    #Close setPanel
  )
  #PAge end   
)

#Set up Server
#---------------------------
server <- shinyServer(function(session,input,output){
  #Temporal Details
  ##################
  #State
  output$State_selector <- renderUI({
    selectInput(inputId = "State",
                label = "State", multiple = FALSE,
                choices = c( unique(Data..$State)),
                selected =  unique(Data..$State)[1])
  })
  #County selection----
  output$County_selector <- renderUI({
    available0 <- as.character(unique(Data..$County[Data..$State %in% input$State ] ))
    pickerInput(inputId = "County", label = "Select/deselect all + format selected", choices = as.character(unique(available0)), 
                options = list(`actions-box` = TRUE, size = 10,`selected-text-format` = "count > 3"), multiple = TRUE,selected = as.character(unique(available0)))
  })
  #Tract selection----
  output$Tract_selector <- renderUI({
    available1 <- as.character(unique(Data..$GEOID[Data..$State %in% input$State ] ))
    pickerInput(inputId = "Tract", label = "Select/deselect all + format selected", choices = as.character(unique(available1)), 
                options = list(`actions-box` = TRUE, size = 10,`selected-text-format` = "count > 3"), multiple = TRUE,selected = as.character(unique(available1)))
  })

  #Graphics
  ##########################
  #Select final data and chart-----
  output$county_plot <- renderPlotly({
    #Select data
    dat <- Data..[Data..$State%in%input$State & Data..$County%in%input$County & Data..$GEOID%in%input$Tract ,]
    #Set up axis parameters depending on amount of data 
    angle = 90

    #Initialze chart
    ggplotly(ggplot(data = dat, x=GEOID, y = ALAND, fill = State) +
               geom_bar(aes(x=GEOID, y = ALAND, fill = State),color = "black", position = "dodge", stat = "identity")+
                ggtitle(paste("Land Area of Select Counties ",unique(dat$State),sep="")) + 
               #Center plot
               theme(plot.title = element_text(hjust = 0.5)) +
               ylab("LAnd Area") +
               xlab("") +
               guides(color=guide_legend("State")) +
               theme(axis.text.x = element_text(angle = angle, hjust = 1),plot.background = element_rect(fill = "darkseagreen"))) %>% layout(dragmode = "select") 

  })
  #Select final data and map-----
  output$map_plot <- renderLeaflet({
    #Select data
    Map_Data_Sp <- Tracts_Sp[Tracts_Sp@data$State%in%input$State,]

    #Create map 
    Map <- mapview(Map_Data_Sp, map.types = "OpenStreetMap", legend = FALSE, col.regions = "red",color = "black",cex = 10)
    Map@map

    #Close map
  })


})
#Run App
shinyApp(ui,server)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...