Reputation: 18585
I'm working on a simple ShinyApp that would enable end-users to interrogate the data with use of various filters. Some of the filters correspond to unique values in data frame columns which are created using the code corresponding to the example below:
# Source sample data
data(mtcars)
# Put together menu element
mtcars$cyl <- as.character(mtcars$cyl)
ui_list_cyl <- unique(mtcars$cyl)
I' subsequently introducing elements created in this manner to the Shiny drop down widget, like in the code below:
# Sample widget elements that provides access to unique column values
selectInput("select", label = h3("Select box"),
choices = ui_list_cyl,
selected = 1),
I'm repeating the same procedure for a number of columns and it creating a function that would address this requirement appears to be a natural choice. In particular, I would envisage for the function to:
ui_list_originalCOLUMname
My question would be: how to create a function that can be dynamically applied to an arbitrary selection of columns in a data frame and will return objects with names incorporating the passed column names?
Upvotes: 0
Views: 84
Reputation: 26313
There's several ways to write the function you want. Here's an example of such a function that accepts a dataset and a column name and creates the associated select input.
mySelectInput <- function(data, col) {
id <- sprintf("select_%s", col)
label <- sprintf("Select %s", col)
choices <- sort(unique(data[[col]]))
selectInput(id, label, choices)
}
You can use it in a shiny app like so
runApp(shinyApp(
ui = fluidPage(
lapply(c("cyl", "gear", "carb"), function(x) mySelectInput(mtcars, x))
),
server = function(input, output, session) {
}
))
This will create three select inputs for the cyl
, gear
, carb
variables. I hope this helps, hopefully you can take it from here and apply it to your need
Upvotes: 1