How to combine vertical cells in tableGrob output tables in R?

I have a question similar to the one here where the OP is aimed at combining the column headers present in the horizontal merge table . Here I want to combine groups of cells that are vertically aligned. The following is my target table design made in Microsoft Excel software: -

enter image description here

My attempt to create a target table using the method asked for a horizontal merge question

library(gridExtra)
library(grid)
library(ggplot2)

alphabets <- c(rep("A", 3), rep("B", 3), rep("C",3))
numbers <- c(rep(c(1,2,3), 3))
sounds <- c('Ayes','Bees','Cees')

df1 <- data.frame(alphabets = alphabets,numbers=numbers)
df2 <- data.frame(sounds = sounds)

tab1 <- tableGrob(df1,theme = ttheme_default(),row=NULL)
tab2 <- tableGrob(df2,theme = ttheme_default(),row=NULL)

halign <- combine(tab2,tab1, along =1)

grid.draw(halign)

This will give me the following result: -

enter image description here

I have a temporary job. But this will not work if I go down even with the number of cells.

sounds <- c('','Ayes','','','Bees','','','Cees','')
df2 <- data.frame(sounds = sounds)
tab2 <- tableGrob(df2,theme = ttheme_default(),row=NULL)
halign <- combine(tab2,tab1, along =1)
grid.draw(halign)

Output for this: -

enter image description here

, grob- .

, .

Lune3141

+4
1

, tableGrob?

# Set locations you want to put sounds at
df2$toBind <- c(2, 5, 8)

# Set locations to allow merge
df1$toBind <- 1:nrow(df1)

# Merge them together
toPrint <-
  right_join(df2, df1) %>%
  mutate(sounds = ifelse(is.na(sounds)
                         , ""
                         , as.character(sounds))) %>%
  select(-toBind)

grid.table(toPrint, row = NULL)

, , , .

, , sounds. - booktabs LaTeX.

- , . , , "" :

halign$layout[halign$layout$t != 1 &
                halign$layout$l == 1, c("t")] <-
  c(2,5,8,2,5,8)

halign$layout[halign$layout$b != 1  &
                halign$layout$l == 1, c("b")] <-
  c(4,7,10,4,7,10)

grid.draw(halign)

(l == 1), (t != 1 b != 1 ) . , (, , ).

enter image description here

, , tab2 grob.. ,

tab2 <- tableGrob(df2
                  , theme = ttheme_default(core=list(bg_params = list(fill = c("white","darkgrey"), col=NA)) )
                  , rows = NULL)

enter image description here

:

halign_alt <- combine(tab2,tab3, along =1)

halign_alt$layout[halign_alt$layout$t != 1 &
                    halign_alt$layout$l == 1, c("t")] <-
  c(2,5,7,2,5,7)

halign_alt$layout[halign_alt$layout$b != 1  &
                    halign_alt$layout$l == 1, c("b")] <-
  c(4,6,9,4,6,9)

grid.draw(halign_alt)

enter image description here

+1

Source: https://habr.com/ru/post/1655967/


All Articles