0

I have the following shiny app, which consists of a numeric input and as outputs two ggplot-graphics.

library(shiny)

n <- 100
dat <- data.frame(var1 = round(rnorm(n, 50, 10),0),
                  var2 = sample(c("A", "B"), n, replace = TRUE))

# USER INTERFACE
ui <- fluidPage(

    titlePanel("My Sample App"),

    sidebarLayout(
        sidebarPanel(
            numericInput("n", "Number of cases", value=100)
        ),


        mainPanel(
           plotOutput("boxplot"),
           plotOutput("distribution")
        )
    )
)

# SERVER
server <- function(input, output) {

    output$boxplot <- renderPlot({
        ggplot(data = dat, aes(x = var2, y = var1)) + geom_boxplot() + ggtitle("Boxplot")
    })
    output$distribution <- renderPlot({
        ggplot(data = dat, aes(var1)) + geom_histogram() + ggtitle("Histogram")
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

I've been trying to replace n = 10 with n = input$n. However it didn't work and I am unsure, where exactly I have to define the data.frame (inside the server function?). Can someone help please?

1 Answer 1

1

input$n is a reactive variable that can only be used in a reactive context. You can only define a reactive context in the server function, e.g. using reactive. Have a look here for an explanation.

library(shiny)
library(ggplot2)


# USER INTERFACE
ui <- fluidPage(
  
  titlePanel("My Sample App"),
  
  sidebarLayout(
    sidebarPanel(
      numericInput("n", "Number of cases", value=100)
    ),
    
    
    mainPanel(
      plotOutput("boxplot"),
      plotOutput("distribution")
    )
  )
)

# SERVER
server <- function(input, output) {
  
  dat <- reactive({
    data.frame(var1 = round(rnorm(input$n, 50, 10),0),
               var2 = sample(c("A", "B"), input$n, replace = TRUE))
  })
  
  output$boxplot <- renderPlot({
    ggplot(data = dat(), aes(x = var2, y = var1)) + geom_boxplot() + ggtitle("Boxplot")
  })
  output$distribution <- renderPlot({
    ggplot(data = dat(), aes(var1)) + geom_histogram() + ggtitle("Histogram")
  })
}

# Run the application 
shinyApp(ui = ui, server = server)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.