簡體   English   中英

R Shiny:根據用戶輸入切換數據集

[英]R Shiny: Switching datasets based on user input

我正在開發一個閃亮的應用程序,用戶可以上傳自己的數據並獲取一些情節和統計數據。 但是,如果用戶按下特定按鈕,我還想包含一個示例數據集。 重要的是,這些圖應該是被動的,以便用戶在點擊“使用示例數據”按鈕或上傳新文件時獲得更新的圖表。 我嘗試重新創建當前覆蓋數據對象的方法盡可能最好,但只是定義數據對象兩次不會以我希望的方式覆蓋數據。 任何建議表示贊賞。

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)

您可以像這樣使用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 ,這是一個my_data值。 只要此值發生更改, renderPlot函數就會觸發並使用正確的數據。

您可以使用無效值來訪問用戶是選擇使用示例數據集還是使用自己的數據集。 用戶可以選擇使用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM