基于条件输入的闪亮R DT中的列子集

时间:2016-08-24 10:43:39

标签: r shiny data.table

这类似于[我的(Multiple expressions in Shiny R Reactive output)之前的问题!我想在哪里根据selectinput对我的数据进行子集化。我拆分了slect输入并添加了一个以selectinput为条件的复选框。现在我希望只使用if子句调整colum向量,但它不起作用。

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 个答案:

答案 0 :(得分:4)

1)输入名称中的错误:&#34; show.LP&#34; !=&#34; show.lp&#34;

2)你永远不会使用cond.cols所以你的checkBox什么都不做

3)尝试

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

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

更新

检查输入是否存在

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
    }
  })