R Shiny App在本地工作但不在shinyapps.io上工作

时间:2017-12-31 23:31:52

标签: shiny shiny-server

我已经看到这个问题发生在其他人身上,但他们的解决方案对我没用。我有我的app.R文件和.RData文件,在同一个ECWA_Strategic_Planning_Tool目录中包含所需的输入。我跑的时候:

library(rsconnect)
rsconnect::deployApp('C:/Users/mikialynn/Documents/Duke/Spring2017/MP/GISTool/Final/ECWA_Strategic_Planning_Tool')

我在打开的网页上收到以下错误:

错误:发生了错误。检查您的日志或联系应用程序作者进行说明。

然而,我找不到任何错误。我安装了所有的软件包,我使用相对路径等。我正在粘贴我的应用程序中的所有代码。如果有人能发现我做错了什么,我会非常感激!

library(shiny)
library(leaflet)
library(sp)
library(rgdal)
library(rstudioapi) # For working directory
library(raster)
library(RColorBrewer)
library(rgeos) #Maybe use gSimplify to simplify polygon
library(DT) #To make interactive DataTable
library(plotly) #For pie chart
library(ggplot2) # for layout

# Set Working Directory
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

# Load R Workspace
load('Shiny.Strategies.RData')

# UI variables
neigh.names <- levels(merge.proj$View)
neigh.default <- c("Urban7")
dt.names <- c('PARCEL_ID', 'PIN', 'OWNER_NAME', 'SITE_ADDRE', 'OWNER_ADDR', 
'SUM_ACRE', 'LANDUSE_DE', 'LAND_VALUE', 'TOTAL_VALU', 'SALE_PRICE', 
'Pluvial_WtScore', 'Rest_WtScore', 'GI_WtScore', 'SC_WtScore', 
'UNCWI_WtScore', 'Total_Score', 'View')
dt.default <- c('PARCEL_ID', 'Pluvial_WtScore', 'Rest_WtScore', 
'GI_WtScore', 'SC_WtScore', 'UNCWI_WtScore', 'Total_Score', 'View')

# Build UI
ui <- fluidPage(
  titlePanel("ECWA Strategic Planning Tool"),
  HTML('<br>'),

  column(2,
         HTML("<strong>Instructions:</strong><br/><br/>"), 
         HTML("<p>1) Select weights for parameters and click 'Run' to 
initiate tool.<br/><br/>
              2) Use rightside panel to adjust Table and Map Settings.<br/>
<br/>
              3) Use search/sort functions of Table to identify parcels. 
Select row to display Total Score Chart.<br/><br/>
              4) Input View and Parcel ID from Table to Map settings to 
identify parcel in Map.<br/><br/> 
              5) When satisfied with weights, click 'Export Shapefile' to 
save shapefile of all parcels.<p/><br/>"),
         HTML("<strong>Calculate Parcel Scores: </strong><br/>"),
         helpText('The sum of the weights must equal to 1.'),
         sliderInput(inputId = "weightPluvial", label = "Weight for Pluvial 
Flooding",
                     value = 0.20, min = 0, max = 1),
         sliderInput(inputId = "weightRest", label = "Weight for 
Restoration",
                     value = 0.20, min = 0, max = 1),
         sliderInput(inputId = "weightGI", label = "Weight for Green 
Infrastructure",
                     value = 0.20, min = 0, max = 1),
         sliderInput(inputId = "weightSC", label = "Weight for City 
Stormwater Controls",
                     value = 0.20, min = 0, max = 1),
         sliderInput(inputId = "weightUNCWI", label = "Weight for UNCWI",
                     value = 0.20, min = 0, max = 1),
         actionButton("run", "Run"),
         actionButton("export", "Export Shapefile")),

  column(8,
         HTML("<h3><strong>Table Summary</strong></h3>"),
         HTML("<br>"),
         dataTableOutput("table")),
  column(2,
         HTML("<p><br><br></p>"),
         HTML("<h4>Table Settings:</h4>"),
         checkboxGroupInput(inputId = 'show_vars', label = 'Select column(s) 
to display in Table:', choices = dt.names, selected = dt.default),  
         HTML("<strong>Total Score Chart:</strong>"),
         helpText("Please select Table row to display pie chart."),
         plotlyOutput("pie")
  ),

  fluidRow(
    column(8, offset = 2,
           HTML("<br>"),
           HTML("<h3><strong>Map Display</strong></h3>"),
           leafletOutput("map", height = 800),
           HTML("<br><br>")),
    column(2,
           HTML("<p><br><br><br></p>"),
           HTML("<h4>Map Settings:</h4>"),
           checkboxGroupInput(inputId = 'show_neigh', label = 'Select 
View(s) to display in Map:', choices = neigh.names,
                              selected = neigh.default),
           HTML("<br>"),
           sliderInput("range", "Select score range to display in Map:", min 
= 0.0, max= 10.0, value = as.numeric(c("0.0", "10.0")), step = 0.1),
           HTML("<br>"),
           HTML("<strong>Parcel Zoom:</strong>"),
           helpText("The View and Score Range must contain the parcel of 
interest to execute zoom."),
           numericInput('parcel','Enter Parcel ID',0)
    )
  ))

    # SERVER

server <- function(input, output) {
  defaultData <- 
    eventReactive(input$run, {
      # Multiply by Weights
      merge.proj@data$Pluvial_WtScore <- 
round(merge.proj@data$Pluvial_Score*input$weightPluvial, digits = 1)
      merge.proj@data$Rest_WtScore <- 
round(merge.proj@data$Rest_Score*input$weightRest, digits = 1)
      merge.proj@data$GI_WtScore <- 
round(merge.proj@data$GI_Score*input$weightGI, digits = 1)
      merge.proj@data$SC_WtScore <- 
round(merge.proj@data$SC_Score*input$weightSC, digits = 1)
      merge.proj@data$UNCWI_WtScore <- 
round(merge.proj@data$UNCWI_Score*input$weightUNCWI, digits = 1)
      # Find Total Score
      merge.proj@data$Total_Score <- merge.proj@data$Pluvial_WtScore + 
merge.proj@data$Rest_WtScore + merge.proj@data$GI_WtScore + 
merge.proj@data$SC_WtScore + merge.proj@data$UNCWI_WtScore
      return(merge.proj)
    })


  # Subset by neighborhood

  neighData <- reactive ({
    merge.proj <- defaultData()
    merge.proj[merge.proj$View%in%input$show_neigh,]
  })


  # Plot with leaflet

  # Palette for map
  colorpal <-  reactive({
    merge.proj <- neighData()  
    colorNumeric(palette = "YlOrRd",
                 domain = merge.proj$Total_Score)
  })
  # Pop Up Option for map
  #  popup <- paste0("<strong>Parcel ID: </strong>", 
  #                  merge.proj@data$PARCEL_ID, 
  #                  "<br><strong>Total Score: </strong>", 
  #                  merge.proj@data$Total_Score)


  # Label Option for map
  labels <- reactive({  
    merge.proj <- neighData()  
    sprintf("<strong>Parcel ID: </strong>%s<br/><strong>Total Score: 
</strong>%g", 
            merge.proj$PARCEL_ID, 
            merge.proj$Total_Score) %>% lapply(htmltools::HTML)
  })

  # Render Default Map
  output$map <- renderLeaflet ({ 
    merge.proj <- neighData()
    pal <- colorpal()
    lab <- labels()
    leaflet() %>% 
      #addProviderTiles(provider='Esri.WorldImagery') %>%
      #      setView(zoom =) %>%
      addTiles() %>%
      addPolygons(
        #data = merge.proj[input$show_neigh,, drop = FALSE],
        data=merge.proj,
        fillColor = ~pal(Total_Score),
        weight = 1,                              
        opacity = 1,
        color = "white",
        dashArray = "3",
        fillOpacity = 0.7,
        highlight = highlightOptions(
          weight = 3,                              
          color = "#666",
          dashArray = "",
          fillOpacity = 0.7,
          bringToFront = TRUE),
        #                 popup= popup) %>%
        label = lab,
        labelOptions = labelOptions(
          style = list("font-weight" = "normal", padding = "3px 8px"),
          textsize = "15px",
          direction = "auto")) %>%
      addLegend(position = "bottomleft",pal = pal, opacity = 0.7, values = 
merge.proj$Total_Score, title = "<strong>Total Score</strong>")
  })



  # Build Data Table
  output$table <- renderDataTable({
    merge.proj <- defaultData()
    table.dat <- merge.proj[, c('PARCEL_ID', 'PIN', 'OWNER_NAME', 
'SITE_ADDRE', 'OWNER_ADDR', 'SUM_ACRE', 'LANDUSE_DE', 'LAND_VALUE', 
'TOTAL_VALU', 'SALE_PRICE', 'Pluvial_WtScore', 'Rest_WtScore', 'GI_WtScore', 
'SC_WtScore', 'UNCWI_WtScore', 'Total_Score', 'View')]
    datatable(data = table.dat@data[, input$show_vars, drop = FALSE], 
options = list(lengthMenu = c(5, 10, 20, 30), pageLength = 20), rownames = 
FALSE)
  })

  # Plot-ly

  output$pie <- renderPlotly({
    merge.proj <- defaultData()
    names <- c('Pluvial', 'Rest', 'GI', 'SC', 'UNCWI')
    colors <- c('rgb(128,133,133)', 'rgb(211,94,96)', 'rgb(144,103,167)', 
'rgb(114,147,203)', 'rgb(171,104,87)')
    selectedrowindex <- 
input$table_rows_selected[length(input$table_rows_selected)]
    selectedrowindex <- as.numeric(selectedrowindex)
    df <- data.frame(merge.proj[selectedrowindex, c('Pluvial_WtScore', 
'Rest_WtScore', 'GI_WtScore', 'SC_WtScore', 'UNCWI_WtScore')])
vector <- unname(unlist(df[1,]))

if (!is.null(input$table_rows_selected)) {
  par(mar = c(4, 4, 1, .1))
  plot_ly(labels = names, values = vector, type = 'pie',
          textposition = 'inside',
          textinfo = 'label+percent',
          insidetextfont = list(color = '#FFFFFF'),
          hoverinfo = 'text',
          text = ~paste('Score:', vector),
          marker = list(colors = colors,
                        line = list(color = '#FFFFFF', width = 1)),
          #The 'pull' attribute can also be used to create space between the sectors
          showlegend = FALSE) %>%
    layout(#title = '% Total Score',
      xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
      yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
}
else {return(NULL)}
  })

  # Update map to parcel score slider

  # Subset data
  filteredData <- reactive({
    merge.proj <- neighData()
    merge.proj[merge.proj@data$Total_Score >= input$range[1] & 
merge.proj@data$Total_Score <= input$range[2],]
  })


  # New Palette
  colorpal2 <-  reactive({
    merge.proj <- filteredData()  
    colorNumeric(palette = "YlOrRd",
                 domain = merge.proj$Total_Score)
  })

  # Pop Up Option  
  #  popup <- paste0("<strong>Parcel ID: </strong>", 
  #                  merge.proj@data$PARCEL_ID, 
  #                  "<br><strong>Total Score: </strong>", 
  #                  merge.proj@data$Total_Score)

  # Label Option
  labels2 <- reactive({  
    merge.proj <- filteredData()  
    sprintf("<strong>Parcel ID: </strong>%s<br/><strong>Total Score: 
</strong>%g", 
            merge.proj$PARCEL_ID, 
            merge.proj$Total_Score) %>% lapply(htmltools::HTML)
  })

  #Leaflet Proxy
  observe({
    merge.proj <- filteredData()
    pal2 <- colorpal2()
    lab2 <- labels2()
    leaf <- leafletProxy("map", data = filteredData()) %>%
      clearShapes() %>%
      addPolygons(
        fillColor = ~pal2(Total_Score),
        weight = 1,                              
        opacity = 1,
        color = "white",
        dashArray = "3",
        fillOpacity = 0.7,
        highlight = highlightOptions(
          weight = 3,                             
          color = "#666",
          dashArray = "",
          fillOpacity = 0.7,
          bringToFront = TRUE),
        #   popup= popup) %>%
        label = lab2,
        labelOptions = labelOptions(
          style = list("font-weight" = "normal", padding = "3px 8px"),
          textsize = "15px",
          direction = "auto"))


    if(input$parcel>0){
      sub.dat <- merge.proj[merge.proj$PARCEL_ID==input$parcel,]
      zx <- mean(extent(sub.dat)[1:2])
      zy <- mean(extent(sub.dat)[3:4])
      leaf <- leaf %>% 
        setView(lng=zx,lat=zy,zoom=16)
    }
    leaf
  })

  #Update Legend
  observe({
    proxy <- leafletProxy("map", data = filteredData())

    pal2 <- colorpal2()
    proxy %>% clearControls()
    proxy %>% addLegend(position = "bottomleft",pal = pal2, opacity = 0.7, 
values = ~Total_Score, title = "<strong>Total Score</strong>")
  })

  # Export new shapefile
  #make so that user can choose name and allow overwrite
  observeEvent(input$export, {
    merge.proj <- defaultData()
    writeOGR(merge.proj, dsn = "Data", layer = "Strategies_Output", driver = 
"ESRI Shapefile")
  })
}



shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:0)

问题已解决!我最初的怀疑是正确的。它与.rdata文件有关。它还与在基于Linux的服务器上运行的Shinyapp.io的服务器有关。根据我的阅读,Linux仅处理小写文件路径和扩展名。它可用于.csv文件的原因是因为以所有小写形式保存文件扩展名是很常见的。 .RData文件不是这种情况。使用RStudio IDE和物理“保存工作区”按钮,默认文件扩展名是.RData(区分大小写)。我无法重命名文件扩展名(出于某种原因,我不是最懂技术的人)。与load()函数类似,有save()函数。以前,我按如下方式使用save()文件(请注意最后的大写.RData):

save(df_training_separated_with_models, file = "sample_data_with_models.RData")

但是,在所有小写字母中使用相同的功能可解决此问题:

save(df_training_separated_with_models, file = "sample_data_with_models.rdata")

希望这可以帮助其他可怜的人解决与互联网和其他论坛有关的问题。

干杯!