2015-11-11 67 views
9

考慮以下actionButton演示: http://shiny.rstudio.com/gallery/actionbutton-demo.html閃亮:如何使無功值和默認值初始化

server.R:

shinyServer(function(input, output) { 

    # builds a reactive expression that only invalidates 
    # when the value of input$goButton becomes out of date 
    # (i.e., when the button is pressed) 
    ntext <- eventReactive(input$goButton, { 
    input$n 
    }) 

    output$nText <- renderText({ 
    ntext() 
    }) 
}) 

ui.R:

shinyUI(pageWithSidebar(
    headerPanel("actionButton test"), 
    sidebarPanel(
    numericInput("n", "N:", min = 0, max = 100, value = 50), 
    br(), 
    actionButton("goButton", "Go!"), 
    p("Click the button to update the value displayed in the main panel.") 
), 
    mainPanel(
    verbatimTextOutput("nText") 
) 
)) 

在這個例子中,在按下動作按鈕之前,右邊手邊的面板是空的。相反,我會默認呈現默認值爲「50」的文本。

如何獲取輸出以默認輸入顯示如果動作按鈕尚未按下?

+0

只有在輸入$ goButton> 0時,才能將'nText'設置爲'input $ n',否則顯示50。 –

回答

7
shinyServer(function(input, output) { 
     values <- reactiveValues(default = 0) 

     observeEvent(input$goButton,{ 
      values$default <- input$goButton 
     }) 
     # builds a reactive expression that only invalidates 
     # when the value of input$goButton becomes out of date 
     # (i.e., when the button is pressed) 
     ntext <- eventReactive(input$goButton, { 
      input$n 
     }) 

     output$nText <- renderText({ 
     if(values$default == 0){ 
       50 
     } 
     else{ 
      ntext() 
     } 
     }) 
    }) 
6

observeEvent也需要ignoreNULL作爲記錄here,它可以讓你初始化對象沒有if聲明。

通過將,ignoreNULL = FALSE添加到原始帖子(給出或採取某種格式),verbatimTextOutput顯示50啓動。

這讓我在服務器端有點經濟。

ui <- fluidPage(titlePanel("actionButton test"), 
       sidebarLayout(
        sidebarPanel(
        numericInput(
         "n", 
         "N:", 
         min = 0, 
         max = 100, 
         value = 50 
        ), 
        br(), 
        actionButton("goButton", "Go!"), 
        p("Click the button to update the value displayed in the main panel.") 
       ), 
        mainPanel(verbatimTextOutput("nText")) 
       )) 

server <- function(input, output) { 

    ntext <- eventReactive(input$goButton, { 
    input$n 
    } 
    # Adding this parameter to the original example makes it work as intended 
    # with 50 in the output field to begin with 
    , ignoreNULL = FALSE 
) 

    output$nText <- renderText({ 
    ntext() 
    }) 
} 

shinyApp(ui = ui, server = server) 
相關問題