2016-08-24 98 views
0

這與[mine(Multiple expressions in Shiny R Reactive output))的先前問題類似!我希望能夠根據selectinput來對數據進行子集化。我分割了選定的輸入並添加了一個有選擇輸入條件的複選框。現在我希望只用一個if子句來調整colum向量,但它不起作用。在輸入姓名根據條件輸入在閃亮的R DT中進行子集劃分

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

回答

4

1)錯字: 「show.LP」= 「show.lp」

2)你從來不會使用cond.cols所以你的複選框,什麼都不做

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

謝謝你的工作,但對於我在R個接收 警告一個錯誤:錯誤的,如果:變量是長度爲零 堆棧跟蹤(最內側的第1號): 86 :反應性cond.cols [#12] 75:cond.cols 74:EVAL 73:EVAL 72:[.data.table 71:[ 70:頭 69:renderTable [#22] 68: func 67:output $ view 1:runApp 感謝您找到我的排字錯誤8(我真的需要== TRUE嗎?我認爲輸入$ show.LP已經是TRUE/FALSE?第二個條件是多餘的,因爲只有第二個條件爲TRUE時,輸入$ show.LP才存在。 –

+0

這是因爲你沒有'輸入$ show.LP'當應用程序啓動(見更新) – Batanichek

+0

你不需要== TRUE,但以這種方式容易承受。第二個條件需要(在我的R),因爲如果你檢查輸入$ show.LP,然後改變輸入$ life.pension你看到兩列 – Batanichek

相關問題