简体   繁体   English

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

[英]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 )! 这类似于先前的问题[mine( Shiny R Reactive输出中的多个表达式 where I wanted to be able to subset my data based on a selectinput. 我希望能够基于selectinput对数据进行子集化。 I split the slect input and added a checkbox conditional on the selectinput. 我拆分了选择输入,并在selectinput上添加了一个复选框。 Now I was hoping to just adjust the colum vector with a if clause, but it does not work. 现在,我希望仅使用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) Typo in names of inputs: "show.LP" != "show.lp" 1)输入名称中的错字:“ show.LP”!=“ show.lp”

2) You never use cond.cols so your checkBox do nothing 2)您从不使用cond.cols因此您的checkBox不执行任何操作

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

and head(DT[LP==input$life.pension,.SD,.SDcols=cond.cols()]) 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
    }
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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