Hi,
The filter
function is part of the dplyr
package. For some reason, it is not an issue if not loaded in Shiny, but you need to explicitly do this for the markdown document it seems. This is my code that is working:
{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(shiny)
library(dplyr)
{r, echo=FALSE}
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("city", "Choose a city:",
choices = "New York",
selected = "New York"),
selectInput("number_of_bedroom", "Choose a room number:",
choices = c(2,3,4),
selected = 2)
),
# Display plot
mainPanel(
tabsetPanel(
tabPanel("Zipcode ranking", dataTableOutput("table"))
)
)
)
)
server <- function(input, output, session) {
df <- data.frame("city" = "New York", "num_of_bedroom" = c(2,3), indicator = c(1,2))
df$city = as.character(df$city)
dataInput <- reactive({
out <- filter(df, city == input$city & num_of_bedroom == input$number_of_bedroom
out
})
output$table <- renderDataTable({
dataInput()
},options = list(lengthMenu = c(30, 60, 100), pageLength = 5))
}
shinyApp(ui, server)
Few extra comments:
- When creating a data frame, you don't need to quote the name of the column:
#This
df <- data.frame("city" = "New York", "num_of_bedroom" = c(2,3), indicator = c(1,2))
#Can be this
df <- data.frame(city = "New York", num_of_bedroom = c(2,3), indicator = c(1,2))
- There is no need in saving your data frame in a local variable and then calling it again to return the frame:
#This ...
dataInput <- reactive({
out <- filter(df, city == input$city & num_of_bedroom == input$number_of_bedroom
out
})
#Can be this...
dataInput <- reactive({
filter(df, city == input$city & num_of_bedroom == input$number_of_bedroom
})
- Finally, you could use a full dplyr implementation
#This....
filter(df, city == input$city & num_of_bedroom == input$number_of_bedroom
#Can be this...
df %>% filter(city == input$city, num_of_bedroom == input$number_of_bedroom )
Hope this helps,
PJ