基于复选框的条件输出

时间:2019-05-16 18:41:31

标签: r shiny

我想填充许多表,但只显示用户请求的表。例如,在下面的最小示例中,我将mtcar拆分为三个表,并且具有三个复选框。我只想在选中相应复选框的情况下显示每个表格。

我尝试使用condiditionalPanel,但是没有用。该应用程序未响应我的输入。也许conditionalPanel仅适用于GUI输入。

## Only run examples in interactive R sessions
if (interactive()) {

  ui <- fluidPage(
    checkboxInput("cyl4", "Show 4 cylinders", value=FALSE),
    textOutput("box4"),
    checkboxInput("cyl6", "Show 6 cylinders", value=FALSE),
    textOutput("box6"),
    checkboxInput("cyl8", "Show 8 cylinders", value=FALSE),
    textOutput("box8"),

    conditionalPanel(
      condition = "input.cyl4 == TRUE",
      tableOutput("data4")
    ),
    conditionalPanel(
      condition = "input.cyl6 == TRUE",
      tableOutput("data6")
    ),
    conditionalPanel(
      condition = "input.cyl8 == TRUE",
      tableOutput("data8")
    )

  )

  server <- function(input, output) {

    output$box4 <- renderText(input$cyl4)
    output$box6 <- renderText(input$cyl6)
    output$box8 <- renderText(input$cyl8)

    output$data4 <- renderTable({mtcars[mtcars$cyl == 4, ]}, rownames = TRUE)
    output$data6 <- renderTable({mtcars[mtcars$cyl == 6, ]}, rownames = TRUE)
    output$data8 <- renderTable({mtcars[mtcars$cyl == 8, ]}, rownames = TRUE)
  }

  shinyApp(ui, server)
}

当前,闪亮的应用程序显示所有三个表,并且不响应复选框。如果仅选中了cyl4框,我希望该应用仅显示表“ data4”。

1 个答案:

答案 0 :(得分:1)

条件参数必须用JavaScript编写,其中TRUE拼写为true。下面的代码应该可以工作。

library("shiny")

shinyApp(

    ui = fluidPage(
        checkboxInput("cyl4", "Show 4 cylinders", value=FALSE),
        textOutput("box4"),
        checkboxInput("cyl6", "Show 6 cylinders", value=FALSE),
        textOutput("box6"),
        checkboxInput("cyl8", "Show 8 cylinders", value=FALSE),
        textOutput("box8"),

        conditionalPanel(
            condition = "input.cyl4 == true",
            tableOutput("data4")
        ),
        conditionalPanel(
            condition = "input.cyl6 == true",
            tableOutput("data6")
        ),
        conditionalPanel(
            condition = "input.cyl8 == true",
            tableOutput("data8")
        )

    ),

    server =function(input, output) {

        output$box4 <- renderText(input$cyl4)
        output$box6 <- renderText(input$cyl6)
        output$box8 <- renderText(input$cyl8)

        output$data4 <- renderTable({mtcars[mtcars$cyl == 4, ]}, rownames = TRUE)
        output$data6 <- renderTable({mtcars[mtcars$cyl == 6, ]}, rownames = TRUE)
        output$data8 <- renderTable({mtcars[mtcars$cyl == 8, ]}, rownames = TRUE)
    }

)