在Shiny

时间:2017-12-22 07:24:28

标签: r csv shiny leaflet r-leaflet

我有一个简单的闪亮应用程序,可以从csv文件输入中绘制点。目前,当我将文件上传到闪亮的应用程序时,地图不会执行任何操作。我认为这是因为传单地图没有对正在上传的文件做出反应。我怎么能解决这个问题?

请参阅下面的代码。可以找到示例数据HERE

library(shiny)
library(shinydashboard)
library(leaflet)
library(dplyr)
library(htmltools)

shinyApp(
  ui <- fluidPage(

    titlePanel("eBird Visualizer"),
    fileInput("MyEBirdData_in", "MyEBirdData", buttonLabel = "Upload a .csv", 
              placeholder = "No File Selected...", width = "255px", 
              accept = ".csv"),
    leafletOutput("myMap")
  ),

  server = function(input, output) {

    output$contents <- renderTable({

      inFile <- input$MyEBirdData_in
      if (is.null(inFile))
        return(NULL)
      myData = read.csv(inFile$datapath, header = input$header)

      df0 = data.frame(myData$Submission.ID, myData$Latitude, myData$Longitude)
      df = unique(df0)
      names(df)[2] = 'latitude'
      names(df)[3] = 'longitude'

    })

    output$myMap = renderLeaflet({

      leaflet(data = df) %>% addProviderTiles(providers$CartoDB.Positron)
    })
  }
)

1 个答案:

答案 0 :(得分:3)

renderTable用于创建要在UI中显示的反应表。你想要的是有一个可以在其他反应式表达式中使用的变量来触发它们更新,在这种情况下你应该使用reactivereactiveValue,例如参见here;在页面下方2/3,他们首先介绍reactive作为一个很好的例子。

此外,您目前指的是未定义的input$header。因此,在上传csv时会出错。

所以你可以这样做:

library(shiny)
library(shinydashboard)
library(leaflet)
library(dplyr)
library(htmltools)

shinyApp(
  ui <- fluidPage(

    titlePanel("eBird Visualizer"),
    fileInput("MyEBirdData_in", "MyEBirdData", buttonLabel = "Upload a .csv", 
              placeholder = "No File Selected...", width = "255px", 
              accept = c(".csv","text/csv")),
    leafletOutput("myMap")
  ),

  server = function(input, output) {

    my_table <- reactive({

      inFile <- input$MyEBirdData_in
      if (is.null(inFile))
        return(NULL)

      myData = read.csv(inFile$datapath)

      df0 = data.frame(myData$Submission.ID, myData$Latitude, myData$Longitude)
      df = unique(df0)
      names(df)[2] = 'latitude'
      names(df)[3] = 'longitude'
      print(df)
      return(df)
    })

    output$myMap = renderLeaflet({
      if(is.null(my_table()))
      {
        return(leaflet()  %>% addProviderTiles(providers$CartoDB.Positron))
      }
      else
      {
        leaflet(data = my_table()) %>% addProviderTiles(providers$CartoDB.Positron) %>% addMarkers()
      }
    })
  }
)