主面板内部是否有R函数具有过滤器

时间:2019-07-03 19:01:05

标签: r shiny

我有一个在大型机内部具有数据框的代码。一旦选择“ ABC”或“ DEF”,数据框就会显示出来,但我需要在此放置一个过滤器。类似于将View(dataobject)放入R studio中时得到的结果

Unit_Price <- c(60, 49, 40, 61, 64, 60, 59, 54, 62, 69, 70, 42, 
                56,61, 61, 61, 58, 51, 48, 65, 49, 49, 41, 48, 52, 46,59, 46, 58, 
                43)
Material <- c("tas", "sa", "qld", "nsw", "nsw", "nt", "wa", 
              "wa","qld", "vic", "nsw", "vic", "qld", "qld", "sa", "tas","sa", 
              "nt", "wa", "vic", "qld", "nsw", "nsw", "wa","sa", "act", "nsw", 
              "vic", "vic", "act")
library(shiny)
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(selectInput("x","Supplier name",choices = 
                               c("ABC","DEF")),
                 checkboxInput("mean","Mean Prices are"),
                 tableOutput("mean")),
    mainPanel(h6("Here it is"),
              tableOutput("message")
    ) 
  ) 
)
server <- function(input, output, session) {
  data <- reactive({
    if (input$x == "ABC") {
      data.frame(Unit_Price, Material)
    } else if (input$x == "DEF") 
    {
      data.frame(Material=c("A","B"), Unit_Price=c(7,8))
    }
  })
  output$message <- renderTable({
    data()
  })
  output$mean <- renderTable(rownames = TRUE, {
    req(input$mean)
    df <- data()
    tapply(df$Unit_Price, df$Material, mean)
  })
}
shinyApp(ui, server)

1 个答案:

答案 0 :(得分:0)

您可以使用DT软件包。在其基本版本中,它为您提供过滤器。

Unit_Price <- c(60, 49, 40, 61, 64, 60, 59, 54, 62, 69, 70, 42, 
                56,61, 61, 61, 58, 51, 48, 65, 49, 49, 41, 48, 52, 46,59, 46, 58, 
                43)
Material <- c("tas", "sa", "qld", "nsw", "nsw", "nt", "wa", 
              "wa","qld", "vic", "nsw", "vic", "qld", "qld", "sa", "tas","sa", 
              "nt", "wa", "vic", "qld", "nsw", "nsw", "wa","sa", "act", "nsw", 
              "vic", "vic", "act")
library(shiny)
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(selectInput("x","Supplier name",choices = 
                               c("ABC","DEF")),
                 checkboxInput("mean","Mean Prices are"),
                 tableOutput("mean")),
    mainPanel(h6("Here it is"),
              DT::dataTableOutput("message")
    ) 
  ) 
)
server <- function(input, output, session) {
  data <- reactive({
    if (input$x == "ABC") {
      data.frame(Unit_Price, Material)
    } else if (input$x == "DEF") 
    {
      data.frame(Material=c("A","B"), Unit_Price=c(7,8))
    }
  })
  output$message <- DT::renderDT({
    data()
  })
  output$mean <- renderTable(rownames = TRUE, {
    req(input$mean)
    df <- data()
    tapply(df$Unit_Price, df$Material, mean)
  })
}
shinyApp(ui, server)

您还可以使用参数filter获取一些高级过滤选项。只需替换以下代码:

  output$message <- DT::renderDT({
    data()
  },filter = "top")