0

I made a shiny-app with the output is here: https://tci123.shinyapps.io/tes5/

In the output the digits of each cells are not the same, and even, some are very long. How to set it so I can get the same digits for shiny data-table ?

my code:

server <- function(input, output, session) {
  
   output <- renderDataTable({
    DT::datatable(df, 
                  selection = "single",
                  filter = 'bottom',
                  extensions = c('Buttons', 'ColReorder', 'FixedHeader', 'Scroller'),
                  rownames = FALSE,
                  options = list(
                    columnDefs = list(list(targets = c(13,14), visible = FALSE)))) %>% 
      formatStyle(columns = "Jan",
                  valueColumns = "jan_goal",
                  backgroundColor = styleEqual(levels = c(0,1,2), 
                                               values = c("#008000","#FFA500","#F00"))) %>% 
      formatStyle(columns = "Feb",
                  valueColumns = "feb_goal",
                  backgroundColor = styleEqual(levels = c(0,1,2), 
                                               values = c("#008000","#FFA500","#F00"))) %>%
      mutate(across(is.numeric, round, digits = 2))  
  })#%>% 
  
  dplyr::output %>%
    mutate(across(is.numeric, round, digits = 2))
  output$df <- output
}
Tugiyo
  • 31
  • 6

1 Answers1

0

If you are looking to round the numbers across all the columns in your df, you can use dplyr package.

Here's how you can do this:

library(dplyr)

df %>%
   mutate(across(is.numeric, round, digits = 2))

It will round all the numeric values from df to 2 digits. You can change the value of digits parameter according to your need.

Vishal A.
  • 1,373
  • 8
  • 19
  • How to put it in the server of shiny: server <- function(input, output, session) { output$df <- renderDataTable({ DT::datatable(df, ..... – Tugiyo Feb 22 '22 at 10:02
  • You can do that before `outpu$df`. – Vishal A. Feb 22 '22 at 10:04
  • Error: no applicable method for 'mutate' applied to an object of class "c('datatables', 'htmlwidget')" – Tugiyo Feb 22 '22 at 10:06
  • Can you edit your question and include the shiny code you are using? – Vishal A. Feb 22 '22 at 10:07
  • OK I will try again – Tugiyo Feb 22 '22 at 10:08
  • There's also `formatRound` function in `DT`. You can find the similar question answered [here](https://stackoverflow.com/questions/31022331/how-to-always-display-3-decimal-places-in-datatables-in-r-shiny) – Vishal A. Feb 22 '22 at 10:11
  • 1
    It is solved by this: formatRound(columns=c('Jan', 'Feb','Mar','Apr','Mei','Jun','Jul', 'Aug','Sep','Oct','Nov','Des'), digits=3) – Tugiyo Feb 22 '22 at 10:40