Wasabi
Wasabi

Reputation: 3071

In Shiny, Is it possible to extract an input value different from what was given (i.e. converting percentage to decimal)?

I've written a percentageInput() function which is just a wrapper around textInput() with some added JS to only allow percentage values. It works fine, rejecting invalid values, etc.

However, the value obtained from input$myPercentage is still in percentage form ("80%"), though getting it in decimal (0.8) would be much easier. I'm currently simply performing this conversion after collecting the value, but this input type is used in many places and it gets repetitive. It'd be much more elegant if I could "intercept" the value returned by input$myPercentage to simply be in decimal form.

The only idea I've had would be setting it up as a module: the UI would be what I currently have and then a server method to do the conversion. But that'd also mean having to initialize each of those servers individually, which is arguably worse.

So, is this possible to do in a relatively "elegant" manner?

Upvotes: 1

Views: 54

Answers (1)

Victorp
Victorp

Reputation: 13856

Best option is to write your own JavaScript bindings, some documentation is available here : https://unleash-shiny.rinterface.com/, and for your specific question see: https://unleash-shiny.rinterface.com/shiny-input-system.html#custom-data-format

Otherwise there's a function in shinyWidgets that allow to create a percentage input:

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  
  tags$h2("Percentage Input"),
  
  autonumericInput(
    "id", "Percent:", 
    value = 0.23, 
    suffixText = "%", 
    rawValueDivisor = 100, 
    decimalPlaces = 1,
    maximumValue = 100,
    minimumValue = 0,
    wheelOn = "focus"
  ),
  verbatimTextOutput("res")
)

server <- function(input, output, session) {
  output$res <- renderPrint(input$id)
}

shinyApp(ui, server)

Upvotes: 2

Related Questions