How to create On load Event or default event in shiny?

拟墨画扇 提交于 2019-12-01 08:27:41

Using renderPlot or other render functions inside observeEvent is considered bad practice. What you are looking for is a reactive object that represents the plot parameters. You can then access this reactive object inside your renderPlot context. Here is an example

library(shiny)

ui <- shinyUI(fluidPage(
  titlePanel("Iris Dataset"),
  sidebarLayout(
    sidebarPanel(
      radioButtons("x", "Select X-axis:",
                   list("Sepal.Length" = 'a', "Sepal.Width" = 'b',
                        "Petal.Length" = 'c', "Petal.Width" = 'd')),
      radioButtons("y", "Select Y-axis:",
                   list("Sepal.Length" = 'e', "Sepal.Width" = 'f', 
                        "Petal.Length" = 'g', "Petal.Width" = 'h')),
      actionButton("action", "Submit")
    ),
    mainPanel(
      plotOutput("distPlot")
    )
  )
))

server <- shinyServer(function(input, output) {

  user_choice <- eventReactive(input$action,{
    if (input$x == 'a'){i <- 1}    
    if (input$x == 'b'){i <- 2}    
    if (input$x == 'c'){i <- 3}    
    if (input$x == 'd'){i <- 4}    
    if (input$y == 'e'){j <- 1}    
    if (input$y == 'f'){j <- 2}    
    if (input$y == 'g'){j <- 3}    
    if (input$y == 'h'){j <- 4}

    return(c(i, j))

    ## use ignoreNULL to fire the event at startup
  }, ignoreNULL = FALSE)

  output$distPlot <- renderPlot({
    uc <- user_choice()
    plot(iris[, uc[1]], iris[, uc[2]])
  })
})


shinyApp(ui = ui, server = server)

The object user_choice will get updated whenever a user clicks the button or the app starts.

There is also an ignoreNULL parameter in observeEvent but for some reason, that does not yield the same result.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!