0

How would I format single cells in a data table? Assume I have the following table (tibble):

require(tibble)
test <- tibble(
  Figures = c("a", "b", "c"), 
  "2019" = c(120000, 0.45, 4032), 
  "2020" = c(132000, 0.55, 3431)
)

which looks like this:

> test
# A tibble: 3 x 3
  Figures    `2019`    `2020`
  <chr>       <dbl>     <dbl>
1 a       120000    132000   
2 b            0.45      0.55
3 c         4032      3431   

I would like the first and third row to be displayed with 1000s separator and the second as percentage. The data table output should look approx. like this:

  Figures    2019       2020
  ___________________________
  a       120.000    132.000   
  b            45%        55%
  c         4.032      3.431   

I haven't found a way to apply formatting to a single cell.

PavoDive
  • 6,322
  • 2
  • 29
  • 55
sedsiv
  • 531
  • 1
  • 3
  • 15
  • 1
    Individual columns of a data.frame or tibble are vectors, which will always have the same class. If you want to simply format an output to display, e.g. in a table, format them as characters and use character vectors to display. Check out the `sprintf` and `format` commands. – user12728748 Mar 12 '21 at 14:28
  • I would suggest you reformat your table to keep the same type along columns: most (if not all!) tools are designed for that case. Once you do that, check the packages::functions `DT::formatCurrency`, `DT::formatRound` and `DT::formatPercentage` and `scales::percent`, `scales::dollar` and `scales::comma`. – PavoDive Mar 12 '21 at 14:36

1 Answers1

1

Using this answer, this solution might be for you:

library(tidyverse)
test <- tibble(
  Figures = c("a", "b", "c"), 
  "2019" = c(120000, 0.45, 4032), 
  "2020" = c(132000, 0.55, 3431)
)
test %>% 
  mutate(across(where(is.numeric),
                ~ifelse(.<=1, 
                        paste0(round(. * 100), '%'),
                        format(as.integer(.), big.mark=".", decimal.mark = ','))))
#> # A tibble: 3 x 3
#>   Figures `2019`    `2020`   
#>   <chr>   <chr>     <chr>    
#> 1 a       "120.000" "132.000"
#> 2 b       "45%"     "55%"    
#> 3 c       "  4.032" "  3.431"

Created on 2021-03-12 by the reprex package (v0.3.0)

Max Teflon
  • 1,760
  • 10
  • 16