Home > Mobile >  How to append two tables with same number of columns in kableExtra?
How to append two tables with same number of columns in kableExtra?

Time:12-05

I am trying to make a big table by appending several small tables with the same number of columns using kableExtra. Specifically, suppose I have the following datasets and kables:

library(kableExtra)

df1 <- data.frame(x = c("a","b"), y=1:2)
df2 <- data.frame(x = c("c","d"), y=3:4)

k1 <- kable(df1, format = 'latex') |> 
  add_header_above(c("Header 1 " = 2))

k2 <- kable(df2, format = 'latex') |> 
  add_header_above(c("Header 2" = 2))

I would like to join k1 and k2 in the same table, obtaing as output:

\begin{tabular}{l|r}
\hline
\multicolumn{2}{c}{Header 1 } \\
\cline{1-2}
x & y\\
\hline
a & 1\\
\hline
b & 2\\
\hline
\multicolumn{2}{c}{Header 2} \\
\cline{1-2}
x & y\\
\hline
c & 3\\
\hline
d & 4\\
\hline
\end{tabular}

This would translate in: Table

However, I wouldn't like to join the data frames, because they come from several different aggregations. Can someone help me?

CodePudding user response:

Something like this?

rbind(df1, df2) |>
  kbl() |>
  add_header_above(c("Header 1 " = 2)) |>
  kable_styling(full_width = F)

enter image description here

CodePudding user response:

Welcome to SO! I don't know how to combine the tables directly without first joining the data frames. However, using pack_rows to specify rows for grouping together should work for your purpose.

rbind(df1, df2) %>%
kbl(format = "latex", caption = "Combined Tables") %>%
  kable_paper("striped", full_width = F) %>%
  pack_rows("Header 1", 1, 2) %>%
  pack_rows("Header 2", 3, 4)

The LaTeX code generated is the following.

\begin{table}
\caption{Combined Tables}
\centering
\begin{tabular}[t]{l|r}
\hline
x & y\\
\hline
\multicolumn{2}{l}{\textbf{Header 1}}\\
\hline
\hspace{1em}a & 1\\
\hline
\hspace{1em}b & 2\\
\hline
\multicolumn{2}{l}{\textbf{Header 2}}\\
\hline
\hspace{1em}c & 3\\
\hline
\hspace{1em}d & 4\\
\hline
\end{tabular}
\end{table}

table generated from LaTeX

Check the documentation of ?pack_rows from kableExtra if you want to modify the group labels, add \hlines, or other cosmetic changes.

  • Related