4

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")
    ) 
1
  • Does this works for you i.e. Descs <- Descs %>% mutate(across(where(is.numeric), ~ formattable::comma(.x, big.mark = ",", format = "f", digits = 0))) adn then use kable on that object. The advantage is that it retains the columns as numeric while adding the format
    – akrun
    Mar 21, 2022 at 16:24

2 Answers 2

6

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

1
  • Nice option about the format.args within kable
    – akrun
    Mar 21, 2022 at 16:29
3

You can use this code:

library(kableExtra)
library(dplyr)

Descs <- apply(Descs, 2, function(x) prettyNum(x, big.mark = ","))

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

Output:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.