2

In R one can use options(digits=n) to adjust the number of digits in the output value. However, this does not work in Shiny, and sprintf() does not work with very low numbers either since it would only display zeros. So, how could i obtain in Shiny something like

options(digits = 4)

p.val$p.value [1] 3.724e-23

So that i could use it in the title of the plot in renderPlot?

ForEverNewbie
  • 357
  • 2
  • 10

1 Answers1

2

Instead of changing options, we can simply use signif to set our required number of digits. The following mini app can be modified as necessary to work for plot titles.

library(shiny)
ui <- fluidPage(
  fluidRow(
    column(6,
           
           numericInput(
             "hello_options",
             label = "Number",
             value = 3.145677177118
           )),
    
    column(6, 
           numericInput("digits",
                        label = "Digits",
                        value = 4
                        )
           )
  ),
  
  
  textOutput("out_text")

)

server <- function(input, output, server){
    output$out_text <- renderText(
      signif(input$hello_options, digits = input$digits)
    )
}

shinyApp(ui = ui, server = server)

If you want to format to scientific, then change your server to this. Note however that this gives you characters that should be converted back.

server <- function(input, output, server){
    output$out_text <- renderText(
      format(signif(input$hello_options, digits = input$digits),
             scientific = TRUE)
    )
}

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
  • 1
    Thanks! Did not manage to make a miniapp so fast... By scientific, do you mean the same ouput format as I showed in the question? I tried `signif()` and used it in the `main` argument of `boxplot()` and did not change the initial format, i.e. 3.724e-23 format. – ForEverNewbie Jul 18 '22 at 19:54
  • 1
    Yes, I think the same output as in your question. It seems the output between `signif` and `format` is the same anyway so `format` is probably unnecessary (only that it is more commonly used). – NelsonGon Jul 18 '22 at 19:56