How to do the 2 Group Using gt Package in R?

In R, the `gt` package is used for creating elegant tables. If you want to group two groups of data in a `gt` table, you can use the `tab_spanner()` function to create column groups or `group_by()` + `gt_group()` for row groups.

Example 1: Creating Column Groups (Using `tab_spanner()`)

If you want to group columns under two main categories:

```r
# Load libraries
library(gt)

# Create example data
data <- data.frame(
Category = c("A", "B"),
Group1_Val1 = c(10, 20),
Group1_Val2 = c(15, 25),
Group2_Val1 = c(30, 40),
Group2_Val2 = c(35, 45)
)

# Create a gt table with column groups
gt_table <- data %>%
gt(rowname_col = "Category") %>%
tab_spanner(
label = "Group 1",
columns = c("Group1_Val1", "Group1_Val2")
) %>%
tab_spanner(
label = "Group 2",
columns = c("Group2_Val1", "Group2_Val2")
)

# Print the table
gt_table
```

This will create column groups “Group 1” and “Group 2” above related columns.

Example 2: Creating Row Groups (Using `row_group_order()`)

If you want to group rows under two different groups:

```r
# Create example data
data <- data.frame(
Group = c("Group 1", "Group 1", "Group 2", "Group 2"),
Name = c("Alice", "Bob", "Charlie", "David"),
Score = c(85, 90, 78, 88)
)

# Create a gt table with row groups
gt_table <- data %>%
gt() %>%
tab_row_group(
label = "Group 1",
rows = Group == "Group 1"
) %>%
tab_row_group(
label = "Group 2",
rows = Group == "Group 2"
) %>%
cols_hide(columns = "Group") # Hide the Group column

# Print the table
gt_table
```

This will group the rows under “Group 1” and “Group 2”.