Search code examples
rdatatabletidyversedt

R using formatRound for all numeric columns of a datatable


The following R code can be used to format the first four columns of iris data. Wondering how to format all numeric columns rather than giving their names or positions.

library(tidyverse)
library(DT)

iris %>% 
  datatable() %>% 
  formatRound(1:4, digits = 2)

Solution

  • Perhaps, we can do this before converting to datatable

    library(dplyr)
    library(DT)
    iris %>%
      mutate(across(where(is.numeric), sprintf, fmt = '%.2f')) %>%
      datatable() 
    

    Or another option is to check the 'data' component in the created object

    iris %>% 
         datatable()  %>%
         formatRound(purrr::map_lgl(.$x$data, is.numeric), digits = 2)