LB1234
LB1234

Reputation: 75

How to change number of digits separately for columns in renderTable in R Shiny

I have a table to display in R Shiny, using renderTable, but I would like to change the number of digits only for the second column into 3 digits, and the first and third column into 0 digits. How is this possible?

   output$Table_X <- renderTable({

        outputData <- loadFunc()
        outputData$x
      }, 
      digits = 3)

In the line with outputData <- loadFunc(), the list outputData is created, with a dataframe in it called 'X'. This contains three columns with numeric data. Now it the rendertable displays the data as following:

a               b                 c
0.000           1.123             10.000
2.000           2.345             12.000
4.000           5.789             15.000

I would like to have only column 'b' with 3 number of digits, and column 'a' and 'c'with zero number of digits.

Upvotes: 3

Views: 2081

Answers (1)

bretauv
bretauv

Reputation: 8557

One solution is to use formatRound in package DT. This requires to use dataTableOutput and renderDataTable, and to put your data in datatable():

library(shiny)
library(tibble)
library(DT)

data <- tibble(
  x = c(1.889, 1.289),
  y = c(3.44898, 4.48349),
  z = c(3.4343, 3.1)
)

ui <- fluidPage(
  dataTableOutput("table")
)

server <- function(input, output, session) {

  output$table <- renderDataTable({
    datatable(data) %>%
      formatRound(columns = 2, digits = 3) %>%
      formatRound(columns = c(1, 3), digits = 0)
  })

}

shinyApp(ui, server)

Edit: If you don't want to use dataTableOutput and renderDataTable, you can replace the function formatRound by formatC (in base R), but it is a bit more annoying:

library(shiny)
library(tibble)

data <- tibble(
  x = c(1.889, 1.289),
  y = c(3.44898, 4.48349),
  z = c(3.4343, 3.1)
)

ui <- fluidPage(
  tableOutput("table")
)

server <- function(input, output, session) {

  output$table <- renderTable({
    data$x <- formatC(data$x, digits = 0)
    data$z <- formatC(data$z, digits = 0)
    data$y <- formatC(data$y, digits = 3)
    data
  })

}

shinyApp(ui, server)

Upvotes: 3

Related Questions