Shanvi
Shanvi

Reputation: 33

How to loop through pack_rows in r using kableextra package?

A   C
-------
KK  1
KK  3
KK  3
AA  4
AA  52
BB  33
BB  7
BB  83
DD  91
DD  10

i have a table like the one above i want to use column A and make it into groups and use start and end index to be used in pack_rows to automate using the dataframe above. i tried to use for loop but it didn't work it showing error in loop so how can i loop through using below code

kbl(df,booktabs = T,longtable = T) %>%
kable_styling(latex_options = c("repeat_header"),bootstrap_options = "bordered",font_size = 7,full_width = F)%>%
  row_spec(0, bold = T, color = "white", background = "#008752")%>% 
  pack_rows("KK", 1, 3,background = "#008000")%>%
  pack_rows("AA", 4, 5,background = "#008000")

Upvotes: 2

Views: 627

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

Make A column as factor with levels same as appearance. Use table in pack_rows -

library(knitr)
library(kableExtra)

df$A <- factor(df$A, unique(df$A))

kbl(df,booktabs = T,longtable = T) %>%
  kable_styling(latex_options = c("repeat_header"),
        bootstrap_options = "bordered",font_size = 7,full_width = F)%>%
  row_spec(0, bold = T, color = "white", background = "#008752")%>% 
  pack_rows(index = table(df$A), background = "#008000")

enter image description here

Upvotes: 1

Related Questions