library(gt)
# This is a key step, as gt will create the row groups
# based on first observation of the unique row items
# this sampling will return a row-group order for cyl of 6,4,8
set.seed(1234)
sliced_data <- mtcars %>%
dplyr::group_by(cyl) %>%
dplyr::slice_head(n = 3) %>%
dplyr::ungroup() %>%
# randomize the order
dplyr::slice_sample(n = 9)
# not in "order" yet
sliced_data$cyl
# But unique order of 6,4,8
unique(sliced_data$cyl)
# creating a standalone basic table
test_tab <- sliced_data %>%
gt(groupname_col = "cyl")
# can style a specific column based on the contents of another column
tab_out_styled <- test_tab %>%
tab_style(
locations = cells_body(mpg, rows = gt_index(., am) == 0),
style = cell_fill("red")
)
# OR can extract the underlying data in the "correct order"
# according to the internal gt structure, ie arranged by group
# by cylinder, 6,4,8
gt_index(test_tab, mpg, as_vector = FALSE)
# note that the order of the index data is
# not equivalent to the order of the input data
# however all the of the rows still match
sliced_data
Run the code above in your browser using DataLab