如何使top_n()反应?在函数内使用输入$ x?

时间:2018-06-12 10:08:32

标签: r shiny dplyr top-n

我正在建立一个shinyapp,我有市场和客户的数据。

我想制作一个valueBox,告诉公司的顶级市场, 但我希望用户选择他想看多少个市场(5,10,15,20等)

例如,选择Top 5或Top 10或Top 15等等。

当我应用此代码时,我收到此错误:

ui.r:

  fluidRow( 
                        box(selectInput("topmar", "Select Top", c("5", "10", "15", "20"), selected = 5, width = "80px"), 
                          title = "Top Markets", width = 4, collapsible = TRUE, collapsed = TRUE, background = "light-blue", solidHeader = TRUE, 
                            tableOutput("top5market")),

server.r:

topmarket <- reactive({
    comcon() %>% 
      group_by(Market) %>% 
      summarize(CollectiveTurnover = sum(`Net turnover`)) %>% 
      arrange(desc(CollectiveTurnover)) %>% 
      # top_n(5)
      input$topmar <- as.numeric(top_n(input$topmar)) 
      top_n(input$topmar)
  })

screenshot of the code and error

这是我得到的错误:

  

没有适用于'tbl_vars'的方法应用于类的对象   “字符”

1 个答案:

答案 0 :(得分:0)

我想您快到了,但是您将selectInput选项作为字符提供了。 这是一个工作示例:

library(shiny)
library(shinydashboard)
library(dplyr)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody( fluidRow( 
    box(selectInput("topmar", "Select Top", c(5, 10, 15, 20), selected = 5, width = "80px"), 
        title = "Top Markets", width = 4, collapsible = TRUE, collapsed = TRUE, background = "light-blue", solidHeader = TRUE, 
        tableOutput("topMarketTable")))
  ))

server <- function(input, output) {
  comcon <- reactive({tibble(Market = paste0("Market_", rep(LETTERS[1:20], 100)), `Net turnover` = round(runif(2000, 10000, 20000)))})

  topMarket <- reactive({
    comcon() %>% 
      group_by(Market) %>% 
      summarize(CollectiveTurnover = sum(`Net turnover`)) %>% 
      arrange(desc(CollectiveTurnover)) %>% 
      top_n(n = as.integer(input$topmar), wt = CollectiveTurnover)
  })

  output$topMarketTable <- renderTable(topMarket())

}

shinyApp(ui, server)