简体   繁体   中英

Columns subsetting in shiny R DT based on conditional input

This is similar to a previous questions of [mine( Multiple expressions in Shiny R Reactive output )! where I wanted to be able to subset my data based on a selectinput. I split the slect input and added a checkbox conditional on the selectinput. Now I was hoping to just adjust the colum vector with a if clause, but it does not work.

library(shiny)
library(datasets)


DT<-rbind(data.table(LP=rep("with.LP",3),Total=seq(6,8)+seq(1,3)/2,Life=seq(1,3)/2),
    data.table(LP=rep("wo.LP",3),Total=seq(6,8),Life=0))

Cols<-c("Total")
server<-shinyServer(function(input, output) {

  # renderUI for conditional checkbox in UI for separately
  output$conditionalInput<-    renderUI({
                                 if(input$life.pension=="with.LP"){
                                    checkboxInput("show.LP", "Show separately", FALSE)
                                        }
                                     }) 
  #Condition if input$show.lp == TRUE
  cond.cols<- reactive({
      if(input$show.lp) {
        c(Cols,"Life")}
          })

   # calculate table
  output$view <- renderTable({
    head(DT[LP==input$life.pension,.SD,.SDcols=Cols])
  })
})

# Define UI for dataset viewer application
ui<-shinyUI(fluidPage(

  # Application title
  titlePanel("Shiny Example"),
  # Sidebar with controls to select a dataset and specify the
  # number of observations to view
  sidebarLayout(
    sidebarPanel(
     selectInput("life.pension", label = h3("Include L&P?"),
                    choices = list("Yes" = "with.LP", "No" = "wo.LP")
                                    ,selected = "with.LP"),
          uiOutput("conditionalInput")
    ),

    # Show a summary of the dataset and an HTML table with the 
     # requested number of observations
    mainPanel(
      tableOutput("view")
     )
  )
))
runApp(list(ui=ui,server=server))

1) Typo in names of inputs: "show.LP" != "show.lp"

2) You never use cond.cols so your checkBox do nothing

3)Try

#Condition if input$show.lp == TRUE
  cond.cols<- reactive({
    if(input$show.LP==TRUE & input$life.pension=="with.LP") {
      c(Cols,"Life")
    }else{
        Cols
      }
  })

and head(DT[LP==input$life.pension,.SD,.SDcols=cond.cols()])

Update

check if input exists

cond.cols<- reactive({
    if(!is.null(input$show.LP)){
    if(input$show.LP==TRUE & input$life.pension=="with.LP") {
      c(Cols,"Life")
    }else{
      Cols
    }}else{
      Cols
    }
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM