I am trying to extract the label of the selected option in a radio button. For example, I have a radio button called 'dist' and selected option is 'norm'
ui <- fluidPage(
radioButtons("dist", "Distribution type:",
c("Normal" = "norm",
"Uniform" = "unif",
"Log-normal" = "lnorm",
"Exponential" = "exp")),
plotOutput("distPlot")
)
server <- function(input, output) {
x1 = input$dist
print(x1) # gives 'norm' but I want 'Normal'
}
shinyApp(ui, server)
I wanted to know the simplest method to implement this without using any outside construct like javascript etc.
First of all, the code provided does not work - the server code needs to be wrapped in observe({ ... })
in order for it to function.
As for your question - there are two ways to approach this.
If the options are known ahead of time and are not dynamic, you can define the list of options as a separate variable that is accessible for both the UI and the server (if the ui and server are defined in separate files, then place it in a global.R
file). Then simply look up the name based on the value.
dist_options <- c("Normal" = "norm",
"Uniform" = "unif",
"Log-normal" = "lnorm",
"Exponential" = "exp")
ui <- fluidPage(
radioButtons("dist", "Distribution type:", dist_options),
plotOutput("distPlot")
)
server <- function(input, output) {
observe({
x1 = input$dist
print(names(which(dist_options == x1)))
})
}
shinyApp(ui, server)
If the options are dynamic, you will need to get involved with custom javascript code. Shiny will need to ask javascript for the label value of a specific input based on its value, and javascript will need to communicate it back to shiny.