2015-07-21 48 views
1

我是新來的閃亮和做簡單閃亮的應用程序,它產生iid正常變量和打印直方圖。 輸入有:閃亮生成隨機值,每次按下按鈕

  • 2 numericInput字段,mu和sigma
  • ActionButton

輸出是tabsetPanel:

  • TAB1:5個生成的值
  • TAB2:直方圖

所以它不起作用。我嘗試了很多變體,只有不充分的工作解決方案是這樣的。

這裏是代碼ui.R

library(shiny) 
library(xtable) 

meanInput1 <- numericInput("id1", "$$mean \\ of \\ x_1$$", 1, min = -10, max = 10, step = 1) 
meanInput2 <- numericInput("id2", "$$sd \\ of \\ x_2$$", 1, min = -10, max = 10, step = 1) 
tabPanel1 <- tabPanel("generated values", tableOutput("table1")) 
tabPanel2 <- tabPanel("Plot", plotOutput("plot1")) 

shinyUI(fluidPage(
    withMathJax(), 
    titlePanel("title"), 

    sidebarLayout(
     fluid=TRUE, 

     sidebarPanel(
      meanInput1, 
      meanInput2, 
      actionButton("goButton", "Go!") 
     ), 
    mainPanel(

     tabsetPanel(
      tabPanel1, 
      tabPanel2 
     ) 
    ) 
))) 

這裏是代碼server.R

shinyServer(
    function(input, output) { 

     output$plot1 <- renderPlot({ 
      if (input$goButton >= 1){ 
       sigma <- input$id2 
       muInput <- input$id1 

       table <- as.data.frame(rnorm(n = 5,muInput,sd = sigma)) 
       names(table) <- "x" 

       output$plot1 <- renderPlot(hist(table)); 
       output$table1 <- renderTable(head(table)); 
      } 
     }) 
    } 
) 

問題:

  • 只有buttonClicked 一次和tabPanel2選擇它的工作原理。每次點擊一個按鈕時如何使它工作。

回答

0

在這種情況下,您希望使用eventReactive。你可以找到使用actionButtonhere的演示。您的代碼在渲染語句中使用渲染語句的結構也有些奇怪。

如果您創建eventReactive函數並分離出您的renderTablerenderPlot調用它更清晰並正常工作。爲了清楚起見,不要將變量命名爲函數,因此我將table變量更改爲my_table也是一種很好的做法。

shinyServer(
    function(input, output) { 

    rand <- eventReactive(input$goButton,{ 
     sigma <- input$id2 
     muInput <- input$id1 

     my_table <- as.data.frame(rnorm(n = 5,muInput,sd = sigma)) 
     names(my_table) <- "x" 
     return(my_table) 
    }) 

    output$plot1 <- renderPlot({ 
     my_table <- rand() 
     if(is.null(my_table)){ 
     return(NULL) 
     }else{ 
     hist(head(my_table$x)); 
     } 
    }) 


    output$table1 <- renderTable({ 
     my_table <- rand() 

     if(is.null(my_table)){ 
     return(NULL) 
     }else{ 
     my_table 
     } 
    }); 
    } 
)