R Shiny:根据用户输入切换数据集

时间:2019-08-01 08:16:27

标签: r shiny reactive

我正在开发一个闪亮的应用程序,用户可以上传自己的数据并获取一些图表和统计信息。但是,我还想提供一个示例数据集,如果用户按下特定按钮,该数据集将被使用。重要的是,这些图应该是反应性的,以便用户单击“使用示例数据代替”按钮或上载新文件时可以获取更新的图。我试图重新创建当前最好的覆盖数据对象的方法,但是仅仅两次定义数据对象并不会像我希望的那样覆盖数据。任何建议表示赞赏。

library(shiny)

# UI
ui <- fluidPage(

    # Application title
    titlePanel("Reproducible Example"),

    # Sidebar with a slider input for number of bins 
    sidebarLayout(
        sidebarPanel(

            fileInput("Upload", "Upload your own Data"),

            actionButton("Example", "Use Example Data instead")

        ),

        # Show a plot of the generated distribution
        mainPanel(

            plotOutput("hist")

        )
    )
)

# Server Logic
server <- function(input, output) {

        data <- eventReactive(input$Upload,{input$Upload})
        data <- eventReactive(input$Example, {faithful$eruptions})

        output$hist <- renderPlot({hist(data())})

}

# Run the application 
shinyApp(ui = ui, server = server)

2 个答案:

答案 0 :(得分:1)

您可以像这样使用reactiveVal

server <- function(input, output) {
   my_data <- reactiveVal()
   observeEvent(input$Upload, {
      tmp <- read.csv(input$Upload$datapath)
      ## do whatever is needed to parse the data
      my_data(tmp)
   })
   observeEvent(input$Example, {
      my_data(faithful)
   })
   output$hist <- renderPlot({
       dat <- as.data.frame(req(my_data()))
       dat <- dat[, sapply(dat, is.numeric), drop = FALSE]
       validate(need(NCOL(dat) > 1, "No numeric columns found in provided data"))
       hist(dat[,1])
   })
}

取决于上传或单击按钮,您将数据存储在my_data中,这是一个无功值。每当此值更改时,renderPlot函数就会触发并使用正确的数据。

答案 1 :(得分:1)

您可以使用反应性值来访问用户是选择使用示例数据集还是使用自己的数据集。用户可以使用您的UI输入选择在活动数据集之间切换。

这是RStudio对反应性值的正式解释:link

这将进入您的ui.R

radioButtons("sample_or_real",    
    label = h4("User data or sample data?"),
    choices = list(
        "Sample Data" = "sample",
        "Upload from user data" = "user",
    ), 
    selected = "user"
)

这将进入您的server.R

data_active <- reactive({

  # if user switches to internal data, switch in-app data
  observeEvent(input$sample_or_real_button, {

  if(input$sample_or_real == "sample"){
    data_internal <- sample_data_object
  } else {
    data_internal <- uploaded_data_object
  }
})

请注意,在server.R文件中使用反应性值时,它必须在对象名称的末尾带有括号()。因此,您将data_internal对象称为data_internal()

相关问题