Search code examples
rdplyrforcatsgt

How can I reorder row labels in the r package gt?


I am trying to reorder the row labels in a gt table but, for some reason, it seems like the forcats function I'm using is being ignored by gt. Here's a reproducible example to illustrate what I mean:

(1) Here's what the exibble dataset (which comes with gt) looks like as a table using only the variables group, char and currency:

library(gt)
library(tidyverse)

exibble %>% 
  select(group, char, currency) %>% 
  gt(groupname_col = 'group',
     rowname_col = 'char')  

Photo of the resulting table:

enter image description here

(2) Let's say I want to be able to reorder the row labels so that char is ordered from largest to smallest fruit within each group. It should end up looking like this:

Photo of the ideal table:

enter image description here

(3) So I releveled char and expected the row labels in the table to be displayed in this new order:

exibble %>% 
  mutate(charOrdered = fct_relevel(char, c('durian', 'coconut', 'banana', 'apricot', 'honeydew', 'grapefruit', 'fig'))) %>% 
  select(group, charOrdered, currency) %>% 
  gt(groupname_col = 'group', 
     rowname_col = 'charOrdered')

However, it's as if gt has ignored the forcats function and kept the order of the new variable, charOrdered, alphabetical. Any idea why this is happening and how I can reorder row labels?

Photo of the resulting table (which is identical to the first table):

enter image description here

I'm using R 4.0.2, dplyr 1.0.2, forcats 0.5.0 and gt 0.2.2 on macOS Catalina 10.15.6.

I'm new to R and stack overflow, so any constructive feedback on how to better phrase questions is welcome and would be appreciated. Thank you!


In case you were wondering, I created the ideal table in (2) by creating vectors. However, this approach is not ideal as it is inefficient and prone to errors.

exibble %>% 
  mutate(fruit = c('durian', 'coconut', 'banana', 'apricot', 'honeydew', 'grapefruit', 'fig', NA)) %>% 
  mutate(currency = c('65100.000', '1.390', '17.950', '49.950', '0.440', NA, '13.255', '1325.810')) %>% 
  select(group, fruit, currency) %>% 
  gt(groupname_col = 'group', rowname_col = 'fruit') 

Solution

  • Just arrange by charOrdered:

    exibble %>% 
      mutate(charOrdered = fct_relevel(char, c('durian', 'coconut', 'banana', 'apricot', 'honeydew', 'grapefruit', 'fig'))) %>% 
    
      arrange(charOrdered) %>%
    
      select(group, charOrdered, currency) %>% 
      group_by(group) %>%
      gt(groupname_col = 'group', 
         rowname_col = 'charOrdered')
    

    enter image description here