Use shiny text input and dplyr to filter rows in a dataframe

こ雲淡風輕ζ 提交于 2019-12-21 06:34:28

问题


I am trying to use the text input widget on a shiny app to filter rows in a data frame but I can’t get it working.

Dataset

df1<-data.frame (Name=c("Carlos","Pete","Carlos","Carlos","Carlos","Pete","Pete","Pete","Pete","Homer"),Sales=(as.integer(c("3","4","7","6","4","9","1","2","1","9"))))

UI

shinyUI(fluidPage(
titlePanel("Sales trends"),titlePanel("People score"),

sidebarLayout(sidebarPanel(

  textInput("text", label = h3("Text input"), value = "Enter text..."),

  numericInput("obs", "Number of observations to view:", 3),

  helpText("Note: while the data view will show only the specified",
           "number of observations, the summary will still be based",
           "on the full dataset."),

  submitButton("Update View")
),

mainPanel(
  h4("Volume: Total sales"),
  verbatimTextOutput("volume"),

  h4("Top people"),
  tableOutput("view")
))))

Server

library(shiny)
library (dplyr)
df1<-data.frame (Name=c("Carlos","Pete","Carlos","Carlos","Carlos","Pete","Pete","Pete","Pete","Homer"),Sales=(as.integer(c("3","4","7","6","4","9","1","2","1","9"))))
shinyServer(function(input, output) {
output$value <- renderPrint({ input$text })
datasetInput <- reactive({
switch(input$dataset,df1%>% filter(Name %in% "input$text")%>% select(Name, Sales)%>% arrange(desc(Sales)))
})
output$volume <- renderPrint({
dataset <- datasetInput()
sum(dataset$Sales)
})})

回答1:


As aosmith pointed out, you need to remove the quotes for filtering. Second, you should use == instead of %in% inside of filter(). Third, you would use switch() in other cases (read up on ?switch), but here you don't need it.

Your server.R should look like this:

library(shiny)
library(dplyr)
df1 <- data_frame(Name = c("Carlos","Pete","Carlos","Carlos","Carlos","Pete",
                         "Pete","Pete","Pete","Homer"),
                  Sales = c(3, 4, 7, 6, 4, 9, 1, 2, 1, 9))

shinyServer(function(input, output) {
  datasetInput <- reactive({
    df1 %>% filter(Name == input$text) %>% arrange(desc(Sales))
  })
  output$volume <- renderPrint({
    dataset <- datasetInput()
    dataset$Sales
  })
})



回答2:


when you filter with your own search words,
1. make update function with: reactive
2. input the function within renderDT

ui = fluidPage(
        textInput('qry', 'Species', value='setosa'),
        DT::DTOutput('tbl'))
server = function(input, output){
        a = reactive({ filter(iris, Species == input$qry })
        output$tbl = renderDT(a())
shinyApp(ui,server)

good luck!



来源:https://stackoverflow.com/questions/32844736/use-shiny-text-input-and-dplyr-to-filter-rows-in-a-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!