1
votes

I am new to shiny and do simple shiny application, which generates iid normal variables and prints histogram. The input has:

  • 2 numericInput fields, mu and sigma
  • ActionButton

Output is tabsetPanel:

  • Tab1: 5 generated values
  • Tab2: histogram

So it does not work. I tried a lot variants and only insufficiently working solution was this.

Here is code 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
        )
    )
)))

Here is code 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));
            }
        })
    }
)

Questions:

  • It works only if buttonClicked once and tabPanel2 is selected. How to make it work every time I click a button.
1

1 Answers

0
votes

You want to use eventReactive in this case. You can find demos for using the actionButton here. You also have somewhat strange structure to your code with render statements inside of render statements.

If you create your eventReactive function and separate out your renderTable and renderPlot calls it is much clearer and works correctly. It is also good practice to not name variables the same as functions so I changed the table variables to my_table for clarity.

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