I am building an Rshiny app where the input data will always have the same structure but different categories. No matter what that data looks like, I always want my filters to display the same values. I followed some examples and thought this would work, but I am having trouble setting a default selection.
Additionally I am curious if I will need to do anything to the server when I use these alternate display names in a filter for my plots and tables or if this is just purely edits to the Ui?
The data would have a structure like this,
but the values of "col_1" and "col_2" will always differ.
No matter what those values are, I always want the first value of "col_1"
to appear in the Ui "Filter 1" as "Segment 1" and the first
value of "col_2" to appear as "Group A" in "Filter 2" and so on...
col_1 <- c("Seg 1", "Seg 2")
col_2 <- c("A", "B")
x<-data.frame(Seg, Group)
#My ui looks something like this
....
pickerInput("Segment", "Filter 1",
choices = c("Segement 1" =(x$Seg[1])[1],
"Segment 2" = (x$Seg[2])[2]),
selected = 'Segment 1', multiple = TRUE),
cellWidths = c("10%", "89%")
),
pickerInput("product_line", "Filter 2", multiple = TRUE,
choices = c("Product A" = levels(x$Group[1]),
"Product B" = levels(x$Goup[2])),
selected = "Product A"),
....
With my actual data, my filter looks like this. How can I get the default selection to appear?
I guess you want something like the following:
library(shiny)
library(shinyWidgets)
random_numbers <- as.integer(runif(5, 1, 26))
col_1 <- paste("Seg", random_numbers)
col_2 <- LETTERS[random_numbers]
seg_choices <- seq_along(col_1)
names(seg_choices) <- paste("Segment", seg_choices)
grp_choices <- seq_along(col_2)
names(grp_choices) <- paste("Product", LETTERS[grp_choices])
ui <- fluidPage(
pickerInput("segment", "Filter 1",
choices = seg_choices,
selected = seg_choices[1], multiple = TRUE),
pickerInput("product", "Filter 2",
choices = grp_choices,
selected = grp_choices[1], multiple = TRUE),
textOutput("selections")
)
server <- function(input, output, session) {
selectedSegments <- reactive({
col_1[as.integer(input$segment)]
})
selectedProducts <- reactive({
col_2[as.integer(input$product)]
})
output$selections <- renderPrint({cat("selectedSegments: ", paste(selectedSegments(), collapse = ", "), " selectedProducts: ", paste(selectedProducts(), collapse = ", "))})
}
shinyApp(ui = ui, server = server)
The choices are provided via an index rather than directly using the elements of the underlying data, which is to be filtered.