Format the column names of a table for publication

You are making a table for publication, and you want to change the table’s column names.

Step 1 - Start with a data frame that contains the values that you want to display in the arrangement that you want to display them.

Step 2 - Use gt::gt() to turn your data frame into an editable, professional looking table.

Step 3 - Use gt::cols_label() to change the column names. Set each existing name to its new name, as a string.

data %>% 
  gt() %>% 
  cols_label(
    col_A = "New A",
    col_B = "New B"
  )

Example

store_sales describes the number of various Quaker oatmeal products sold at three stores during a week.

store_sales
# A tibble: 4 × 4
  product                    store8 store21 store44
  <chr>                       <int>   <int>   <int>
1 Quaker Instant Grits 12 oz     20      12       3
2 Quaker Kids Choice 14.3 oz      3       7      11
3 Quick Quaker Oats 18 oz        55      21      53
4 Quick Quaker Oats 42 oz       123      18      52

Before we publish the table, we’d like to change the column labels. To do this, we load the gt package and then convert our data frame to a gt table. Then we use cols_label() to change the column labels in our table.

store_sales %>% 
  gt() %>% 
  cols_label(
    product = "Oatmeal Product",
    store8 = "Store 8",
    store21 = "Store 21",
    store44 = "Store 44"
  )
Oatmeal Product Store 8 Store 21 Store 44
Quaker Instant Grits 12 oz 20 12 3
Quaker Kids Choice 14.3 oz 3 7 11
Quick Quaker Oats 18 oz 55 21 53
Quick Quaker Oats 42 oz 123 18 52

Bold column labels

To make the column labels bold, wrap the label in double asterisks for bold and gt::md() to interpret text as Markdown formatting.

store_sales %>% 
  gt() %>% 
  cols_label(
    product = md("**Oatmeal Product**")
  )

Set column labels in SAS tables

In SAS, to set the format of a variable’s values, you use the FORMAT procedure before manipulating the data in the next procedure where you call the created format.

In R, you create the table and then convert it to publication quality. However, in SAS you create the table and make it look nice all in the same step.

In SAS:

PROC FORMAT;
  value $store_format 'store8' = 'Store 8'
                      'store21' = 'Store 21'
                      'store44' = 'Store 44';
RUN;

PROC TABULATE DATA = quaker_sales;
  CLASS product store_id;
  VAR units_sold;
  FORMAT store_id $store_format;
    TABLE product = 'Product',
      (SUM = '') * (units_sold = '') * (store_id = '');
RUN;

In R:

quaker_sales %>% 
  pivot_wider(
    names_from = store_id,
    values_from = units_sold
  ) %>% 
  gt() %>% 
  cols_label(
    product = "Product",
    store8 = "Store 8",
    store21 = "Store 21",
    store44 = "Store 44"
  )