Search code examples
rgt

Renaming row values in gt() tables


I'm trying to remove string from at gt() table, but without success. In my table I want multiple column names/titles covering two columns named "Day 0", "Day 4", "Day 10", "Day 17" and sub columns named "mean" and "se". Probably easier to understand when looking at the data.

What I want right now is to remove the "day 0" (or e.g. "day 4") from the sub column. Any suggestions?

My code:

library(gt)

gt(mean_se)%>%
  tab_spanner(label = "Day 0", columns = matches("0")) %>%
  tab_spanner(label = "Day 4", columns = matches("4")) %>%
  tab_spanner(label = "Day 10", columns = matches("10")) %>%
  tab_spanner(label = "Day 17", columns = matches("17")) %>%
  tab_header(
    title = md("Biogenic volatile organic compound emissions"))
  
  # str_remove(mean_se, "day 0")
  # rename("mean"=="mean day 0")

Here's the data:

mean_se <- structure(list(mass = c("i.x33.031", "i.x35.034", "i.x36.017", 
"i.x39.959", "i.x40.023"), `mean day 0` = c("241.82", "0.36", 
"1.78", "0.2", "1.82"), `se day 0` = c("241.82", "0.36", "1.78", 
"0.2", "1.82"), `mean day 4` = c("32.94", "0.14", "0", "0", "1.74"
), `se day 4` = c("32.94", "0.14", "0", "0", "1.74"), `mean day 10` = c("266.28", 
"0.6", "0", "0", "1.58"), `se day 10` = c("266.28", "0.6", "0", 
"0", "1.58"), `mean day 17` = c("451.4", "0.48", "0", "0", "2.94"
), `se day 17` = c("451.4", "0.48", "0", "0", "2.94")), row.names = c(NA, 
-5L), class = "data.frame")

Solution

  • One approach is with cols_label. This function accepts individuals arguments to rename a specific column, for example "mean day 0" = "mean". But it's a lot of work to type all those out. Instead, we can use .list = and provide a named list of all the columns we want to rename.

    We can just repeat "mean" and "se" the appropriate number of times and name that character vector with the column names:

    setNames(rep(c("mean","se"),(ncol(mean_se)-1)/2),names(mean_se)[-1])
    # mean day 0    se day 0  mean day 4    se day 4 mean day 10   se day 10 mean day 17   se day 17 
    #     "mean"        "se"      "mean"        "se"      "mean"        "se"      "mean"        "se" 
    

    To keep the order correct, we can use cols_move.

    gt(mean_se)%>%
      tab_spanner(label = "Day 0", columns = matches("0")) %>%
      tab_spanner(label = "Day 4", columns = matches("4")) %>%
      tab_spanner(label = "Day 10", columns = matches("10")) %>%
      tab_spanner(label = "Day 17", columns = matches("17")) %>%
      cols_label(.list = setNames(rep(c("mean","se"),(ncol(mean_se)-1)/2),
                                  names(mean_se)[-1])) %>%
      cols_move(columns = names(mean_se)[-1], after = names(mean_se)[1]) %>%
      tab_header(
        title = md("Biogenic volatile organic compound emissions"))
    

    enter image description here