Reputation: 469
I'm trying to use a checkboxGroupInput
in order to select the registers to be shown. But when filtering the data through multiple conditions it does not work. This is the code I'm using (the data used can be downloaded here):
library(shiny)
ui <- fluidPage(
titlePanel("Shiny Pokédex"),
sidebarLayout(
sidebarPanel(
checkboxGroupInput("Generation", "Select Generation:",
c("First" = 1,
"Second" = 2,
"Third" = 3,
"Forth" = 4,
"Fifth" = 5,
"Sixth" = 6),
inline = T)
),
mainPanel(
dataTableOutput("Generation")
)
)
)
server <- function(input, output) {
pokemon <- read.csv("pokemon.csv")
output$Generation <- renderDataTable({
pokemon[pokemon$Generation == input$Generation,-11]
})
}
shinyApp(ui = ui, server = server)
My goal is to be able to filter more than one generation at the same time. When doing it only with one condition it works, but when clicking on more than one option the output is not as expected.
Upvotes: 0
Views: 1107
Reputation: 160407
You are using ==
, which is intended for specific equality. That is:
1 == 1
# [1] TRUE
1 == 2
# [1] FALSE
But when you start doing multiples on one side or the other:
1 == c(1,2)
# [1] TRUE FALSE
In this case, it says that "1 is equal to 1, 1 is not equal to 2", which is not quite what you want.
where the one TRUE
is recycled over all rows, returning everything.
Let's try %in%
:
1 %in% 1
# [1] TRUE
1 %in% c(1,2)
# [1] TRUE
c(1,3,4) %in% c(1,2)
# [1] TRUE FALSE FALSE
This has the desired properties of set-membership and returning a logical
vector of the same length as the left-hand side of the operator.
Applying to your use, just change the one reactive component to:
output$Generation <- renderDataTable({
pokemon[pokemon$Generation %in% input$Generation,-11]
})
Upvotes: 1