collapse only the 1st column of dataframe in R with remaining columns data intact

206 Views Asked by At

I am new to R and I have a dataframe like below

    
Gender Not_Hired Division Hired Total %Hired Odds
Male    490        F       31   521   6.0   0.063
Male    193        E       74   267   27.7  0.383
Male    389        D      193   582   33.2  0.496
Male    286        C      167   453   36.9  0.584
Male    289        B      493   782   63.0  1.706
Male    437        A      715   1152  62.1  1.636
Female  442        F      33    475   6.9   0.075
Female  417        E      131   548   23.9  0.314
Female  341        D      183   524   34.9  0.537
Female  546        C      282   828   34.1  0.516
Female  11         B      24    35    68.6  2.182
Female  27         A      124   151   82.1  4.593

And I am looking for an output like Output

I tried below code

output %>% 
   select(Division, everything()) %>%
   group_by(Division) %>% ungroup() %>%
  kbl(caption = 'Company wide hiring',
      col.names = c('','','Hired','Not Hired','Total','%Hired','Odds(Hired)'),
      digits = 3) %>%
  kable_styling()

And getting below output: My Output

How do I get from my output to desired output. Any suggestions/ideas?

1

There are 1 best solutions below

0
On BEST ANSWER

Looks like you want to use collapse_rows on the first column. However, to prepare the data for kable output, would make sure to have Division and Gender as the first two columns, and use arrange by Division so the rows with common Division are next to each other.

library(magrittr)
library(kableExtra)

df %>%
  select(Division, Gender, everything()) %>%
  arrange(Division) %>%
  kbl(caption = 'Company wide hiring',
      col.names = c('','','Hired','Not Hired','Total','%Hired','Odds(Hired)'),
      digits = 3) %>%
  kable_styling() %>%
  collapse_rows(columns = 1)

Output

table with collapse_rows on first column