Add commas every digits in numbers of kable()
Asked Answered
E

2

6

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")
    ) 
Expatriate answered 21/3, 2022 at 16:20 Comment(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 formatMullein
C
8

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

Curacy answered 21/3, 2022 at 16:27 Comment(1)
Nice option about the format.args within kableMullein
N
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

Njord answered 21/3, 2022 at 16:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.