I have created a shiny web-page and in the sidebarPanel I use several numericInput-fields. Some of them should display values as percentage and it should not be a slider. Does someone have an idea how to format the numericInput-fields?
2 Answers
2
votes
I can think of two ways of doing that.
1. Formatted Content
Use a text field in the and parse the content in the server code. The solution can only handle integers at this point. Basically, it works. However, interacting with it does not always give you the best usability.
ui <- fluidPage(
titlePanel("Parsed Input with Unit Example"),
textInput("inpPercent", "Chances of Success", value = "20 %"),
h1(textOutput("txtSuccess"))
)
server <- function(session, input, output) {
observeEvent( input$inpPercent,{
Format <- "^[-+]?[ ]*[0-9]*[ ]*[%]?$"
# Trim
inp <- gsub("^\\s+|\\s+$", "", input$inpPercent)
if (!grepl(Format, inp)) {
Result <- "Invalid format"
inp <- numeric()
} else {
# Remove all spaces
inp <- gsub("[[:space:]]", "", inp)
# Split
if (grepl("%", inp)) inp <- gsub("%", "", inp)
inp <- suppressWarnings( as.numeric(inp) )
if (is.na(inp)) {
Result <- "Invalid format2"
inp <- numeric()
} else {
Result <- paste("Percent:", inp)
}
}
print(Result)
output$txtSuccess <- renderPrint(Result)
if (length(inp) > 0)
updateTextInput(session, inputId = "inpPercent", value = paste(inp, "%"))
})
}
2. Shiny Widgets: numericInputIcon
Use the widget numericInputIcon from the shinyWigdets package. It is very easy to set up a widget like that. The documentation provides an example for percentages, too.