根据 selectInput Shiny 读取不同的 excel 数据框

问题描述 投票:0回答:1

我有一个闪亮的应用程序,我希望根据 selectInput 的选择传递来自不同 Excel 文件的数据帧。我尝试使用observeEvent和if...else语句,如示例所示,但没有成功。谁能指导我更好的方法来处理这个问题?对于每个选择,我必须从不同的 Excel 文件中读取 12 个数据帧,并将它们传递到类似命名的数据帧以进行后续数据操作。

library(shiny)
library("xlsx")


ui <- fluidPage(
  
  # Application title
  titlePanel("Reactive Dataframes"),
  
  
  sidebarLayout(
    sidebarPanel(
      selectInput(
        inputId = "selectData",
        label = " Select Data",
        selected = NULL,
        choices = c("mtcars", 
                    "iris")),
      
    ),
    
    mainPanel(
      tableOutput('table')
    )
  )
)

# 
server <- function(input, output) {
  
  observeEvent(input$selectData, {
    if (input$selectData == "mtcars") {
      data1 <-  read.xlsx('data/mtcars.xlsx',
                          sheet = 1, startRow = 8)
      }else{
        data1 <-  read.xlsx('data/iris.xlsx',
                            sheet = 1, startRow = 8)
      }
  })
  
  output$table <- renderTable({ data1 })
}

# Run the application 
shinyApp(ui = ui, server = server)
r shiny shinydashboard shinyapps r-xlsx
1个回答
0
投票

observeEvent
返回一个可观察值。你需要一个
reactive
。所以这会起作用:

library(shiny)
library(xlsx)

ui <- fluidPage(
  titlePanel("Reactive Dataframes"),
  sidebarLayout(
    sidebarPanel(
      selectInput(
        inputId = "selectData",
        label = " Select Data",
        selected = NULL,
        choices = c("mtcars", "iris"))
    ),
    mainPanel(
      tableOutput('table')
    )
  )
)

server <- function(input, output) {
  myData <- reactive ({
    req(input$selectData)
    
    # read.xlsx(
    #   file.path("data", paste0(input$selectData, ".xlsx")), 
    #   sheetIndex = 1
    # )
    # Remove this code and uncomment above in your implementation
    if (input$selectData == "mtcars") mtcars
    else iris
  })

  output$table <- renderTable({ 
    req(myData())
    
    myData() 
  })

您说“并将它们传递给类似命名的数据帧以进行后续数据操作”。我不清楚你在这里的意思以及你为什么要这样做。我认为您需要提供更多信息 - 并发布一个新问题 - 才能得到答案。

© www.soinside.com 2019 - 2024. All rights reserved.