Mark Miller
Mark Miller

Reputation: 13123

Subset data in R Shiny using Multiple Variables

I am new to R Shiny. I am attempting to create an app that allows a user to subset a data.frame based on multiple variables and then see the resulting data.

Here is a small example data set:

iter,wave,apples
1,1,600
1,1,500
1,1,400
1,2,300
1,2,200
1,2,100
2,1,1000
2,1,1100
2,1,1200
2,2,1300
2,2,1400
2,2,1500
3,1,1100
3,1,2200
3,1,3300
3,2,4400
3,2,5500
3,2,6600

I would like the user to be able to specify the value of iter and of wave and see the resulting data.

Here is my attempt at the Shiny code. I realize I must be making several silly mistakes.

Edit

Here is my revised code. The end result now comes pretty close to what I want. The sidebar is still not being displayed perfectly.

library(shiny)

setwd('C:/Users/mark_/Documents/simple_RShiny_files/explore')

apple.data <- read.csv('subset_data_based_on_multiple_variables.csv', 
                        header = TRUE, stringsAsFactors = FALSE)

ui <- fluidPage(

     titlePanel("Subsetting Apple Dataset"),

     sidebarLayout(
          sidebarPanel(
               uiOutput("codePanel")
          ),

          mainPanel(
               tableOutput("view")
          )
     ),

     selectInput("codeInput", inputId ="data1", label = "Choose Iter", choices = unique(apple.data$iter)),
     selectInput("codeInput", inputId ="data2", label = "Choose Wave", choices = unique(apple.data$wave))

)

server <- function(input, output) {

     output$codePanel <- renderUI({

     })

     dataset <- reactive({

          subset(apple.data, (iter == input$data1 & wave == input$data2))

     })

     output$view <- renderTable(dataset())

}

shinyApp(ui = ui, server = server)

The output

enter image description here

Upvotes: 1

Views: 584

Answers (1)

Ahorn
Ahorn

Reputation: 3876

The problem is that both selectInputs have the same inputId. This works:

library(shiny)

apple.data <- data.frame(
        iter = c(1L,1L,1L,1L,1L,1L,2L,2L,2L,2L,2L,
                 2L,3L,3L,3L,3L,3L,3L),
        wave = c(1L,1L,1L,2L,2L,2L,1L,1L,1L,2L,2L,
                 2L,1L,1L,1L,2L,2L,2L),
      apples = c(600L,500L,400L,300L,200L,100L,1000L,
                 1100L,1200L,1300L,1400L,1500L,1100L,2200L,3300L,4400L,
                 5500L,6600L)
)

ui <- fluidPage(
    titlePanel("Subsetting Apple Dataset"),
    sidebarLayout(
        sidebarPanel(
            selectInput("codeInput1", label = "Choose Iter", choices = unique(apple.data$iter)),
            selectInput("codeInput2", label = "Choose Wave", choices = unique(apple.data$wave))
        ),
        mainPanel(
            tableOutput("view")
        )
    )
)

server <- function(input, output) {


    dataset <- reactive({
        return(subset(apple.data, (iter == input$codeInput1 & wave == input$codeInput2)))
    })

    output$view <- renderTable(dataset())
}

shinyApp(ui = ui, server = server)

Upvotes: 2

Related Questions