# formattedFlextable

    library(presenter)
    library(dplyr)
    library(ggplot2)
    library(stringr)

# Custom formatting

- create a header word using `dplyr::rename_with`
- format percentages with `presenter::format_percent`

    diamonds %>%
      select(-clarity) %>%
      mutate(relative_price = price / max(price), .before = "x") %>%
      group_by(across(where(is.ordered))) %>%
      summarize(across(where(is.double), mean), .groups = "drop") %>%
      format_percent(relative_price) %>%
      rename_with(~str_c("category_", .), cut:color) %>%
      rename_with(~str_c("property_", .), carat:table) %>%
      rename_with(~str_c("dimension_", .), x:z) -> diamonds_summary

    diamonds_summary %>% head
    #> # A tibble: 6 × 9
    #>   category_cut categor…¹ prope…² prope…³ prope…⁴ relat…⁵ dimen…⁶ dimen…⁷ dimen…⁸
    #>   <ord>        <ord>       <dbl>   <dbl>   <dbl> <formt>   <dbl>   <dbl>   <dbl>
    #> 1 Fair         D           0.920    64.0    59.0 23%        6.02    5.96    3.84
    #> 2 Fair         E           0.857    63.3    59.4 20%        5.91    5.86    3.72
    #> 3 Fair         F           0.905    63.5    59.5 20%        5.99    5.93    3.79
    #> 4 Fair         G           1.02     64.3    58.8 23%        6.17    6.11    3.96
    #> 5 Fair         H           1.22     64.6    58.7 27%        6.58    6.50    4.22
    #> 6 Fair         I           1.20     64.2    59.2 25%        6.56    6.49    4.19
    #> # … with abbreviated variable names ¹​category_color, ²​property_carat,
    #> #   ³​property_depth, ⁴​property_table, ⁵​relative_price, ⁶​dimension_x,
    #> #   ⁷​dimension_y, ⁸​dimension_z

Header words are automatically identified by the following regular expression: `"^.*(?=(_|\\.))"`. Leaving the `header_word` argument blank produces the same result as providing the commented out argument below. The last id column controls merging and greyscaling. Numeric columns are given some automatic formatting within the `make_flextable` function.

    diamonds_summary %>%
      make_flextable(last_id_col = 2,
                     # header_words = c("category", "property", "dimension"),
                     theme = "zebra_gold")

## Automatic coloring

    tibble(x = letters[1:10],
           y = -5:4,
           z = -c(-.5, -.2, -.1, 0, .1, .2, .3, .4, .6, .9)) %>%
      format_percent(z) %>%
      rename_with(~str_c("sample_", .)) %>%
      make_flextable()

    tibble(x = letters[1:10],
           y = -5:4,
           z = -c(-.5, -.2, -.1, 0, .1, .2, .3, .4, .6, .9)) %>%
      format_percent(z) %>%
      make_flextable()