Custom Formats in gt Tables
Contents
The “grammar of tables” is used to build tables with the R-package gt. Thomas Mock published an extension package called gtExtras which is used all over in tweets about NFL and Fantasy Football such as win and loss history information in a table.
gt
follows a similar philosophy such as ggplot2
. On the one hand there is the data
to be shown (in a table resp. a plot). On the other hand there is the description
how to visualize the data: What is the table header, are there subheaders, how
are the cells grouped and formated?
So it was time to check out gt
. During my tryouts I came across one demand
I haven’t found an in-built solution for: I wanted to format a column with respect
to the value of another column. Here’s the way I solved it:
Sample data
Let’s start with some sample data
|
|
First gt-table
and create a simple gt
-table
|
|
case | value | status |
---|---|---|
a | 18.7095845 | ok |
b | -0.6469817 | unknown |
c | 8.6312841 | ok |
d | 11.3286260 | not ok |
e | 9.0426832 | unknown |
That’s great! That’s a pretty table with just one command!
Colored column based on its own values
Now let’s format the column value
depending on its value:
|
|
case | value | status |
---|---|---|
a | 18.7095845 | ok |
b | -0.6469817 | unknown |
c | 8.6312841 | ok |
d | 11.3286260 | not ok |
e | 9.0426832 | unknown |
Colored column based on value of another column
But now we want to format the column depending on the value
in column status
:
When status
is ok show a green background in column value
, in case of “not okay”
a red one, otherwise show a yellow background.
|
|
case | value | status |
---|---|---|
a | 18.7095845 | ok |
b | -0.6469817 | unknown |
c | 8.6312841 | ok |
d | 11.3286260 | not ok |
e | 9.0426832 | unknown |
As you can see I built a custom function custom_tab_style
.
Within this function I used the function tab_style
and a arbitrary conditions
to format the cells depending on the condition.
Hide the status column
Last we want to hide the column status
. We can achieve this by using
cols_hide()
|
|
case | value |
---|---|
a | 18.7095845 |
b | -0.6469817 |
c | 8.6312841 |
d | 11.3286260 |
e | 9.0426832 |