Home > OS >  R using formatRound for all numeric columns of a datatable
R using formatRound for all numeric columns of a datatable

Time:02-26

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)

CodePudding user response:

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)

CodePudding user response:

A possible solution:

iris %>% 
  datatable() %>% 
  formatRound(which(sapply(iris,is.numeric)), digits = 2)
  • Related