2016-02-21 58 views
0

我正在處理NCAA運動會議收入數據。我希望用戶首先選擇一個會議(例如「ACC」或「BigTen」)。然後,我想要一個滑動條來顯示該會議中學校的最低和最高收入。在selectInput在Shiny之後過濾sliderInput的數據集?

我的數據(在一個名爲colleges表)看起來是這樣的:

conf school   incomeMillions 
ACC  NorthCarolina 105.1 
ACC  Duke   110.2 
ACC  Clemson  94.1 
BigTen OhioState  150.9 
BigTen Minnesota  67.6 
Pac12 California  54.3 
Pac12 Oregon   76.5 
... 

這裏是我到目前爲止的代碼:

runApp(list(
    ui <- bootstrapPage(
    sidebarLayout(
     sidebarPanel(
     selectInput(inputId = "conference", 
        label = "Choose a conference", 
        choices = unique(colleges$conf), 
        multiple = FALSE) 
    ) 
    ), 
    uiOutput("conference") 
), 
    server = function(input, output){ 
    table <- colleges[conf == input$conf], 
    minZ <- round(min(table$incomeMillions), 2), 
    maxZ <- round(max(table$incomeMillions), 2), 
    output$slider = renderUI({ 
     mydata = get(input$range) 
     sliderInput("slider", h3("Z-score range"), min = minZ, max = maxZ) 
    }) 
    } 
)) 

我已經得到了堅持。如何動態過濾該數據集,以便用戶從特定會議的最低和最高收入中進行選擇,而不僅僅是整個數據集?

回答

1

試試這個,它的優點是因爲Shiny很聰明,會緩存data()的輸出,所以即使你多次調用它,也只能評估一次。

library(DT) 
library(data.table) 

ui <- bootstrapPage(
    sidebarLayout(
    sidebarPanel(
     selectInput(inputId = "conf", 
        label = "Choose a conference", 
        choices = unique(as.character(colleges$conf)), 
        multiple = FALSE), 
     uiOutput("slider") 
    ), 
    mainPanel(dataTableOutput("display")) 
) 
) 

server = function(input, output){ 

    data <- reactive({ 
    validate(
     need(input$conf, "Please select a conference.") 
    ) 
    colleges[conf == input$conf] 
    }) 

    output$slider = renderUI({ 
    income <- data()$incomeMillions 

    minZ <- round(min(income), 2) 
    maxZ <- round(max(income), 2) 

    sliderInput("slider", h3("Z-score range"), 
        min = minZ, max = maxZ, value = minZ) 
    }) 

    output$display <- renderDataTable({ 
    data() 
    }) 
} 

shinyApp(ui = ui, server = server)