Skip to content
R for the Rest of Us Logo

Format your table's numbers

If the video is not playing correctly, you can watch it in a new window


Click on the transcript to go to that point in the video. Please note that transcripts are auto generated and may contain minor inaccuracies.

Notice that our table contains a lot of missing numbers. That’s fine but leaving a lot of white space may be off putting to the reader. So, let’s add small dashes to the empty cells.

This demonstrates how to format missing numbers, but it also explains how format any kind of data. Also, this will introduce formulas for selecting specific cells in the table.

penguin_counts_wider |> 
  mutate(island = paste('Island: ', island)) |> 
    groups = 'island'
  ) |> 
  as_flextable(hide_grouplabel = TRUE) |> 
    island = 'Island',
    year = '',
    Adelie_female = 'Female',
    Adelie_male = 'Male',
    Chinstrap_female = 'Female',
    Chinstrap_male = 'Male',
    Gentoo_female = 'Female',
    Gentoo_male = 'Male'
  ) |> 
    values = c('', 'Adelie', 'Chinstrap', 'Gentoo'),
    colwidths = c(1, 2, 2, 2)
  ) |> 
    values = 'Penguins in the Palmer Archipelago\nData is courtesy of the {palmerpenguins} R package'
  ) |> 
  align(i = 2, align = 'center', part = 'header') |> 
  colformat_num(i = ~ (, na_str = '-') |> 

Your Turn

Round the numbers to two decimals with colformat_double(). Your table should look like this:

Have any questions? Put them below and we will help you out!

You need to be signed-in to comment on this post. Login.

soundarya soundararajan

soundarya soundararajan

October 18, 2023

Hi, in this exercise, when I used the colformat_double(digits = 2) function, I seem to get the digits rounded off, but everything ended with 0 instead of what I see here. For eg, instead of 44.44 for Egypt 1957 I got 44.40.

Albert Rapp

Albert Rapp

October 19, 2023

Hi there, that's a bit odd. Can you check what value you get when you extract the specific life expectancy for Egypt?` Try running this code:

selected_countries |> filter(country == 'Egypt') |> pull(year1957 )
# Result should be: 44.444