Julien
Julien

Reputation: 992

Adding two selector inputs that include all columns of a data frame in Shiny app

I'm using a different database than mtcars, but to make this example reproducible I'll use it here.

I'm trying to create an app with a slider and two selectors.

Basically, I know how to create a selectInput if I only choose one column. In the code below, I would simply have selectInput("cylinput", "input", choices = c(all of my choices) and add cyl == input$cylinput to the filter function.

That said, if I want to create two selectInputs for all of the columns in the data frame, then I don't know how to do that. Well, I don't know how to do that once in the server side.

The code is here:

ui:

library(shiny)
library(ggplot2)
library(dplyr)

head(mtcars)

ui <- fluidPage(
  titlePanel("My App"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("mpginput", "mpg", min = 10.4, max = 33.9, value = c(10.4, 33.9)),
      selectInput("xcol", "X Axis", names(mtcars)),
      selectInput("ycol", "Y Axis", names(mtcars))
    ),
    mainPanel(plotOutput("plot1"))
  )
)

server:

server <- function(input, output){

  output$plot1 <- renderPlot({
    Filtered <- mtcars %>%
      filter(
        mpg >= input$mpginput[1],
        mpg <= input$mpginput[2]
      )
    ggplot(Filtered, aes(x = mpg, y = qsec)) +
      geom_point() 
  })
}

shinyApp(ui = ui, server = server)

I did come across this example when researching, and it does something similar to what I'm looking to do. But, I'm not that familiar with base graphics or the code used to create the plot: http://shiny.rstudio.com/gallery/kmeans-example.html

Any help would be greatly appreciated. Thank you.

Upvotes: 0

Views: 126

Answers (1)

Julien
Julien

Reputation: 992

I figured it out. Sorry about the poorly worded question. Honestly, I'm very new to Shiny, and didn't quite understand the code very well.

Basically, all I did was used choices = c() instead of the names(mtcars), which didn't work for me.

Then called the input$xcol and input$ycol in ggplot2 graph.

ui:

library(shiny)
library(ggplot2)
library(dplyr)

head(mtcars)

ui <- fluidPage(
  titlePanel("My App"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("mpginput", "mpg", min = 10.4, max = 33.9, value = c(10.4, 33.9)),
      selectInput("xcol", "X Axis", choices = c("mpg","cyl","hp","drat","disp","wt","gear","carb","am","vs")),
      selectInput("ycol", "Y Axis", choices = c("mpg","cyl","hp","drat","disp","wt","gear","carb","am","vs"))
    ),
    mainPanel(plotOutput("plot1"))
  )
)

server:

server <- function(input, output){

  output$plot1 <- renderPlot({
    Filtered <- mtcars %>% 
      filter(
        mpg >= input$mpginput[1],
        mpg <= input$mpginput[2]
      )
    ggplot(Filtered) +
      geom_point(aes_string(x = input$xcol, y = input$ycol))
  })
}

shinyApp(ui = ui, server = server)

Upvotes: 2

Related Questions