How to save two aligned tables in one image instead of only one huge table in kableExtra?

I have one huge table whose header is "Gênero", "IDH", "Religião", "Nível educacional" e "Voto 2018 - 2º turno". Since it's too big, I want to split the table, so that the two last columns could create a new aligned table below. Then I want to download just one image in which both tables are there.

I tried first with "filter", but it creates a very repeated code and I also get two images. After the download, it's hard to align both tables manually.

My dataframe is:

my_data <- data.frame(" " = c("A favor", "Contra", "Não sei"),
                  "Gênero_Mulher" = c(56, 42, 2), 
                  "Gênero_Homem" = c(52, 43, 5), 
                  "IDH_Baixo" = c(67, 31, 2), 
                  "IDH_Médio" = c(44, 52, 4), 
                  "IDH_Alto" = c(54, 42, 4), 
                  "Religião_Outra religião" = c(66, 31, 2), 
                  "Religião_Católico" = c(57, 39, 3), 
                  "Religião_Agnóstico ou ateu" = c(50, 44, 5), 
                  "Religião_Evangélico" = c(21, 75, 4), 
                  "Nível educacional_Ensino Médio" = c(53, 44, 3), 
                  "Nível educacional_Ensino Superior" = c(54, 41, 4), 
                  "Nível educacional_Ensino Fundamental" = c(72, 28, 0), 
                  "Voto 2018 - 2º turno_Jair Bolsonaro" = c(29, 68, 4), 
                  "Voto 2018 - 2º turno_Fernando Haddad" = c(85, 10, 4), 
                  "Voto 2018 - 2º turno_Votei branco ou nulo" = c(86, 13, 0), 
                  "Voto 2018 - 2º turno_Não compareci para votar" = c(55, 40, 5))

This is my code for now:

cols_1 <- sub("(.*?)_(.*)", "\\2", names(my_data)) # grab everything after the _
grps_1 <- sub("(.*?)_(.*)", "\\1", names(my_data)) # grab everything before the _

# generating table
t <- my_data %>%
  kable(col.names = cols_1, align = "c") %>%
  kable_styling(full_width = F, font_size = 11) %>%
  add_header_above(table(grps_1)[unique(grps_1)], color = "black", 
                   bold = F, 
                   font_size = 13, 
                   line = F,
                   extra_css = "border-bottom:1px solid black;
                   border-right:1px solid black;
                   border-top:1px solid black;
                   border-left:1px solid black;") %>%
  column_spec(1:ncol(my_data), color = "black", width = "8em", include_thead = T,
              extra_css = "border-bottom:1px solid black; border-top:1px solid black;
              border-right:1px solid black; vertical-align: middle;") %>%
  column_spec(1, bold = T, width = "15em", include_thead = F, 
              extra_css = "border-left:1px solid black;")

It should generates something similar to this:
enter image description here

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.