Search code examples
rkablekableextra

Add commas every digits in numbers of kable()


I have the dataframe below and I create a kable out of this. How could I add commas between numbers every 3 digits?

Descs<-structure(list(Mean = c(NaN, 943330388, NaN, NaN, NaN, 543234645, 
45831420, NaN, 27301292, 160818771), Median = c(NaN, 943330388, 
NaN, NaN, NaN, 543234645, 45831420, NaN, 27301292, 160818771), 
    SD = c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, 
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), MAD = c(NA, 
    0, NA, NA, NA, 0, 0, NA, 0, 0), MIN = c(NA, 943330388, NA, 
    NA, NA, 543234645, 45831420, NA, 27301292, 160818771), MAX = c(NA, 
    943330388, NA, NA, NA, 543234645, 45831420, NA, 27301292, 
    160818771), VAR = c(NA_real_, NA_real_, NA_real_, NA_real_, 
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_
    ), RANGE = structure(c(NA, 943330388, NA, NA, NA, 543234645, 
    45831420, NA, 27301292, 160818771, NA, 943330388, NA, NA, 
    NA, 543234645, 45831420, NA, 27301292, 160818771), .Dim = c(10L, 
    2L)), QUANTILES = structure(c(NA, 943330388, NA, NA, NA, 
    543234645, 45831420, NA, 27301292, 160818771, NA, 943330388, 
    NA, NA, NA, 543234645, 45831420, NA, 27301292, 160818771), .Dim = c(10L, 
    2L), .Dimnames = list(NULL, c("25%", "75%")))), row.names = c("Comedy", 
"Education", "Entertainment", "Film & Animation", "Gaming", "Howto & Style", 
"Music", "People & Blogs", "Science & Technology", "Sports"), class = "data.frame")

library(kableExtra)

kable(Descs) %>%
    kable_styling(
      font_size = 15,
      bootstrap_options = c("striped", "hover", "condensed")
    ) 

Solution

  • You could use the kable format argument, this avoids mucking around with the data prior to putting into the table.

    And if you want to clear up the NAs and NaNs you could add in this line of code: options(knitr.kable.NA = '')

    library(kableExtra)
    
    kable(Descs,
          format.args = list(big.mark = ",")) %>%
      kable_styling(
        font_size = 15,
        bootstrap_options = c("striped", "hover", "condensed")
      ) 
    
    

    enter image description here