Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Shiny: How to write loop for observeEvent

I have the following code. Is there any way to write it in a loop or vectorized statement like lapply? In my real code, I have even more brushes so this will be pretty helpful. Thanks.

Ignore this line. Just need to add some more texts.

observeEvent(input$brush_1,{
  Res=brushedPoints(D(),input$brush_1,allRows = TRUE)
  vals$keeprows = Res$selected_
  })

observeEvent(input$brush_2,{
  Res=brushedPoints(D(),input$brush_2,allRows = TRUE)
  vals$keeprows = Res$selected_

})

observeEvent(input$brush_3,{
  Res=brushedPoints(D(),input$brush_3,allRows = TRUE)
  vals$keeprows = Res$selected_

})

observeEvent(input$brush_4,{
  Res=brushedPoints(D(),input$brush_4,allRows = TRUE)
  vals$keeprows = Res$selected_

})

observeEvent(input$brush_5,{
  Res=brushedPoints(D(),input$brush_5,allRows = TRUE)
  vals$keeprows = Res$selected_

})

observeEvent(input$brush_6,{
  Res=brushedPoints(D(),input$brush_6,allRows = TRUE)
  vals$keeprows = Res$selected_

})

observeEvent(input$brush_7,{
  Res=brushedPoints(D(),input$brush_7,allRows = TRUE)
  vals$keeprows = Res$selected_

})

observeEvent(input$brush_8,{
  Res=brushedPoints(D(),input$brush_8,allRows = TRUE)
  vals$keeprows = Res$selected_

})

observeEvent(input$brush_9,{
  Res=brushedPoints(D(),input$brush_9,allRows = TRUE)
  vals$keeprows = Res$selected_

})

observeEvent(input$brush_10,{
  Res=brushedPoints(D(),input$brush_10,allRows = TRUE)
  vals$keeprows = Res$selected_

})

observeEvent(input$brush_11,{
  Res=brushedPoints(D(),input$brush_11,allRows = TRUE)
  vals$keeprows = Res$selected_

})

observeEvent(input$brush_12,{
  Res=brushedPoints(D(),input$brush_12,allRows = TRUE)
  vals$keeprows = Res$selected_

})
like image 446
John Avatar asked Oct 14 '16 08:10

John


1 Answers

observeEvent works great in lapply :

library("shiny")
ui <- fluidPage(
  fluidRow(
    column(
      width = 6,
      lapply(
        X = 1:6,
        FUN = function(i) {
          sliderInput(inputId = paste0("d", i), label = i, min = 0, max = 10, value = i)
        }
      )
    ),
    column(
      width = 6,
      verbatimTextOutput(outputId = "test")
    )
  )
)
server <- function(input, output){

  vals <- reactiveValues()

  lapply(
    X = 1:6,
    FUN = function(i){
      observeEvent(input[[paste0("d", i)]], {
        vals[[paste0("slider", i)]] <- input[[paste0("d", i)]]
      })
    }
  )

  output$test <- renderPrint({
    reactiveValuesToList(vals)
  })
}
shinyApp(ui = ui, server = server)

EDIT : for previous version of shiny, use this in server (add assign) :

lapply(
  X = 1:6,
  FUN = function(i){
    assign(
      paste0("obs", i),
      observeEvent(input[[paste0("d", i)]], {
        vals[[paste0("slider", i)]] <- input[[paste0("d", i)]]
      })
    )
  }
)
like image 70
Victorp Avatar answered Oct 20 '22 14:10

Victorp