0

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?

1
  • Not sure if this is possible in kableExtra as it would involve merging columns, which does not seem to be a feature: stackoverflow.com/questions/58132626/…. You could get part of the way using kableExtra::pack_rows but this would fail to meet your "not to join data frames" criteria. I'm struggling to see how you could manage this without combining data frames as any table created programmatically would invariably include begin and end tabular so some intervention would be required to merge the two latex tabular environements.
    – Peter
    Dec 4, 2021 at 14:59

2 Answers 2

1

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.

0

Something like this?

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

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.