R Shiny:动态行动按钮

时间:2017-06-27 17:44:15

标签: r shiny

我想在Shiny中有一组两个动作按钮,其中inputID和重复数量基于data.frame中的行数。下面附着的是我目前运作正常的思维过程。我不想在按下按钮时添加按钮,而是希望" n"一组按钮等于data.frame中的行数。

library(shiny)

ui <- basicPage(
fluidRow(
 actionButton(inputId = "add_button",
             label = "Add Button")
 ),
 uiOutput("more_buttons")
 )

server <- function(input, output){

 rvs      <- reactiveValues(buttons = list(actionButton(inputId = "button1",
                                                     label = 1)))

observeEvent(eventExpr = input$add_button,
           handlerExpr = {
             len      <- length(rvs$buttons) + 1
             rvs$buttons[[len]] <- actionButton(inputId = paste0("button",len),
                                                label = len)
           })

 output$more_buttons <- renderUI({
  do.call(fluidRow, rvs$buttons)
   })

 observeEvent(rvs$buttons,{
for(ii in 1:length(rvs$buttons)){
  local({
    i <- ii
    observeEvent(eventExpr = input[[paste0("button",i)]],
                 handlerExpr = {print(sprintf("You clicked btn number %d",i))})
  })
  }
 })

}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:4)

以下是您要完成的内容的简化版

ui <- fluidPage(
  selectInput("df", "choose a dataframe",
              c("mtcars", "mpg")),
  uiOutput("buttons")
)

server = function(input, output, session){
  reactiveFrame = reactive({
    if(input$df == "mtcars")
      return(mtcars)
    return(ggplot2::mpg)
  })
  nrowR = reactive({
    nrow(reactiveFrame())
  })
  m <- 0
  output$buttons = renderUI({
    m <- m+1
    do.call(
      fluidPage,
      lapply(
        1:nrowR(),
        function(i)
          span(
            actionButton(paste0("a", i, "-", m),paste0("a", i)),
            actionButton(paste0("b", i, "-", m),paste0("b", i))
          )
      )
    )
  })
}

shinyApp(ui,server)