I'm trying to group the rows of the kable output by the value in the Person column, so the table output is easier to read.
Data for MRE (within an R markdown document, using R Studio 2022.07.1 on Mac OS Ventura 13.2)
library ("tidyverse")
library ("knitr")
Person <- c("A", "A", "B", "B", "C", "C")
Group <- c("pre", "post", "pre", "post", "pre", "post")
Value <- c("10", "5", "8", "4", "5", "4")
df <- tibble(Login,Group,Value)
knitr::kable(df, format = "pipe")
In this output, each row displays its Person value.
I've seen how you can use pack_rows() or group_rows() to manually define groups, but I would like this to be grouped by Person value, rather than be having to define each Person and their relevant two rows.
The current output looks like this
My desired output looks more like this

Using kableExtra::collapse_rows()...
This approach assumes you are printing to pdf. There are multiple options within kableExtra to finetune the appearance of the table.
---
output: pdf_document
---
```{r}
library(tibble)
library (kableExtra)
Person <- c("A", "A", "B", "B", "C", "C")
Group <- c("pre", "post", "pre", "post", "pre", "post")
Value <- c("10", "5", "8", "4", "5", "4")
df <- tibble(Person, Group, Value)
  kbl(df, booktabs = TRUE) |> 
  collapse_rows(valign = "top",
                latex_hline = "major")
```

You could also transform your data to a wider format using pivot_wider like this:
Person <- c("A", "A", "B", "B", "C", "C")
Group <- c("pre", "post", "pre", "post", "pre", "post")
Value <- c("10", "5", "8", "4", "5", "4")
library(tibble)
library(tidyr)
df <- tibble(Person,Group,Value)
df <- pivot_wider(df, names_from = Group, values_from = Value)
knitr::kable(df, format = "pipe")
| Person | pre | post | 
|---|---|---|
| A | 10 | 5 | 
| B | 8 | 4 | 
| C | 5 | 4 | 
Created on 2023-02-06 with reprex v2.0.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With