Xin
Xin

Reputation: 674

How to transform data and add header to table

structure(list(Action = c("ABC", "ABC", "ABC", "ABC", "ABC"), 
               Name = c("Rob", "Cory", "Jack", 
                                  "Mel", "Tina"), cases = c(6L, 
                                                                                          5L, 65L, 1L, 11L), employees = c(6L, 5L, 64L, 1L, 10L), headcount = c(340L, 
                                                                                                                                                                644L, 2259L, 126L, 425L)), row.names = c(NA, -5L), class = c("grouped_df", 
                                                                                                                                                                                                                             "tbl_df", "tbl", "data.frame"), groups = structure(list(Action = "LTD", 
                                                                                                                                                                                                                                                                                     .rows = list(1:5)), row.names = c(NA, -1L), class = c("tbl_df", 
                                                                                                                                                                                                                                                                                                                                           "tbl", "data.frame"), .drop = TRUE))

With the above dataset, how could I transform it so when I use kable(), the resulting table looks like this:

Rob          Cases   employees  headcount
   ABC        6         6       340
Cory 
   Abc        5         5       644

Upvotes: 0

Views: 78

Answers (2)

Ben
Ben

Reputation: 30559

library(tidyverse)
library(kableExtra)
library(knitr)

nameIdx <- data$Name
kable(data[-2]) %>%
  kable_styling(full_width = F) %>%
  group_rows(index = table(fct_inorder(nameIdx)))

Upvotes: 1

Andrew
Andrew

Reputation: 5138

In the past, I have used rle with group_rows to accomplish a similar result:

library(knirt)
library(kableExtra)

rle_obj <- rle(df1$Name)

df1[-2] %>%
  kable() %>%
  kable_styling() %>%
  group_rows(index = setNames(rle_obj$lengths, rle_obj$values))

Upvotes: 1

Related Questions