Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group rows by a variable in R (knitr::kable)

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 thisenter image description here

My desired output looks more like this

enter image description here

like image 650
mda08rds Avatar asked Oct 28 '25 01:10

mda08rds


2 Answers

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")

```

enter image description here

like image 133
Peter Avatar answered Oct 30 '25 16:10

Peter


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

like image 33
Quinten Avatar answered Oct 30 '25 17:10

Quinten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!