Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to order gt in descending order

Could someone show me how I can order the following gt table by year, month, week, and SampleDate? I would like the most recent year to be at the top of the table, which in this case is 2013. Example and screenshot below:

library(dplyr)
library(tidyr)
library(gt)

a <- structure(list(SampleDate = structure(c(15710, 15713, 15713, 
15710, 15710, 15713, 15713, 15710, 15708, 15713, 15712, 15708, 
15708, 15713, 15712, 15708), class = "Date"), year = c("2012", 
"2013", "2013", "2012", "2013", "2013", "2013", "2013", "2013", 
"2012", "2013", "2013", "2013", "2013", "2013", "2013"), F = c(0, 
1, 0, 0, 0, 1, 0, 0, 0, 22, 0, 0, 0, 65, 0, 0), W = c(0, 0, 1, 
0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0), S = c(0, 0, 0, 0, 1, 
0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0), LF = c(1, 0, 0, 1, 0, 0, 0, 
1, 0, 0, 0, 0, 1, 0, 0, 1), week = c("01", "02", "02", "01", 
"01", "02", "02", "01", "01", "02", "02", "01", "01", "02", "02", 
"01"), month = c("January", "January", "January", "January", 
"January", "January", "January", "January", "January", "January", 
"January", "January", "January", "January", "January", "January"
)), row.names = c(NA, -16L), class = "data.frame")

a |>
  mutate(SampleDate = as.character(SampleDate)) |>
  group_by(year, month, week, SampleDate) |>
  summarise(across(c(W, F, LF, S), sum)) |>
  gt() |>
  summary_rows(
    columns = -SampleDate,
    fns =  list(label = "Total", fn = "sum"))

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You may arrange the data first as per your preference before passing it to gt().

library(dplyr)
library(gt)

a |>
  mutate(SampleDate = as.character(SampleDate)) |>
  group_by(year, month, week, SampleDate) |>
  summarise(across(c(W, F, LF, S), sum)) |>
  arrange(desc(year), desc(week)) |>
  gt() |>
  summary_rows(
    columns = -SampleDate,
    fns =  list(label = "Total", fn = "sum"))

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading