R Shiny-引用数据表输出以进行进一步的操作

时间:2020-09-18 10:27:34

标签: r shiny leaflet reactive

我有以下应用可以上传和显示数据文件:

library(shiny)
library(DT)
library(leaflet)

ui <- fluidPage(

  titlePanel('SNP_Review'),
  sidebarLayout(
    sidebarPanel(
    fileInput('target_upload', 'Choose file to upload', accept = c(
      'text/csv',
      'text/comma-separated-values',
      '.csv'
    )),
    ),
    
  mainPanel(
    tabsetPanel(
      type = "tabs",
      tabPanel('Samples_table', DT::dataTableOutput("sample_table")),
      tabPanel('Samples_map', leafletOutput("sample_map"))
      )
    )
  )
)

server <- function(input, output) {
  
  df_products_upload <- reactive({
    inFile <- input$target_upload
    if (is.null(inFile))
      return(NULL)
    df <- read.csv(inFile$datapath, header = TRUE,sep = input$separator)
    return(df)
  })
  
  output$sample_table <- DT::renderDataTable({
    df <- df_products_upload()
    DT::datatable(df)
    
  })
  
  table_data <- reactive({
    
  })
  
  output$sample_map <- renderLeaflet({
    leaflet(data = table_data()) %>%
      addProviderTiles(providers$OpenStreetMap.DE) %>%
      addMarkers(lng = ~Longitude, lat = ~Latitude)
     
  })  
}
 
shinyApp(ui = ui, server = server)

它在表格中打印出我的数据。下一步,我想在带有传单的地图上显示表格的GPS数据。如何在表输出后定义反应性table_data()函数以使用映射中的数据以及可能的进一步操作?该表如下所示:

    Name_ID Population  Latitude Longitude
2 F6537_S01    Finland 60,745411 25,468228
3 N0484_S13     Norway 59,480365  7,920383
4 N0485_S25     Norway 60,925393  10,61182
5 N0486_S37     Norway 62,903547  9,824941
6 N0487_S49     Norway  61,78245 11,918215

谢谢!

1 个答案:

答案 0 :(得分:1)

这正是reactive函数的作用。反应式语句是惰性的,这意味着它们仅被评估一次,直到标记为无效为止,这在其中的反应式语句(例如输入或另一个反应式函数)更改值时发生。只要计算了反应式语句且未标记为无效,则Shiny会将其作为对象来处理。

因此,我会这样更改您的服务器代码

server <- function(input, output) {
  
  df_products_upload <- reactive({
    inFile <- input$target_upload
    if (is.null(inFile))
      return(NULL)
    df <- read.csv(inFile$datapath, header = TRUE,sep = input$separator)
    return(df)
  })
  
  output$sample_table <- DT::renderDataTable({
    df <- df_products_upload()
    DT::datatable(df)
    
  })
  
  output$sample_map <- renderLeaflet({
    leaflet(data = df_products_upload()) %>%
      addProviderTiles(providers$OpenStreetMap.DE) %>%
      addMarkers(lng = ~Longitude, lat = ~Latitude)
     
  })  
}
相关问题