Tam R
Tam R

Reputation: 135

Formatting Numbers in Flextable for Specific Columns

I'm using R version 3.6.1 in RStudio. I have flextable version 0.5.5 and officer version 0.3.5.

I'm having difficulty with formatting my numbers in flextables within RMarkdown. By default, all numbers show up with 3 decimal places. For some of my numbers, this is fine (and actually preferred), but for others, I want to remove the decimals.

Using the advice found here I was able to adjust my table so that all numbers are rounded to the nearest whole number. My code is below (example table used for reproduciblility; otherwise formatting is the same as my current code).

ft_test <- head(iris) %>% flextable() %>% 
    hline(part = 'header', border = fp_border(color = "black", width = 3)) %>% 
    align(align ='center', part = 'all') %>% 
    align(j = 1, align ='left', part = 'all') %>% 
    set_formatter_type(fmt_double = "%.0f")
ft_test

However, I only want certain columns to be whole numbers, and other columns to still have decimals. I've tried using the j argument to call certain columns:

ft_test <- head(iris) %>% flextable() %>% 
    hline(part = 'header', border = fp_border(color = "black", width = 3)) %>% 
    align(align ='center', part = 'all') %>% 
    align(j = 1, align ='left', part = 'all') %>% 
    set_formatter_type(fmt_double = "%.0f", j = 2)
ft_test

... but then I get an error telling me j = 2 is an unused argument.

Any suggestions for how to adjust the numbers of only some columns? Thanks in advance for your help!

Upvotes: 4

Views: 11963

Answers (2)

Jimmy
Jimmy

Reputation: 11

I discovered that you can just do it by running before the creation of the flexible:

set_flextable_defaults(digits = 1)

It worked for me.

Upvotes: 1

David Gohel
David Gohel

Reputation: 10725

You can not use argument j as it is not an argument of set_formatter_type. The function is setting formatters for one or several data type. In your case, it's better to use colformat_num.

library(flextable)
library(officer)
library(magrittr)

ft_test <- head(iris) %>% flextable() %>% 
  hline(part = 'header', border = fp_border(color = "black", width = 3)) %>% 
  align(align ='center', part = 'all') %>% 
  align(j = 1, align ='left', part = 'all') %>% 
  colformat_num(j = c("Sepal.Length", "Sepal.Width",
                             "Petal.Length", "Petal.Width"), digits = 1)
ft_test

enter image description here

You can learn more about formatting content here: https://davidgohel.github.io/flextable/articles/display.html

Upvotes: 5

Related Questions