Reputation: 547
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.
Upvotes: 0
Views: 376
Reputation: 1800
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)
Upvotes: 1