I want to align 2 tables with different column numbers. When using the width function of column spec I get different column widths. In my understanding a column with width 9cm should be as big as 2 columns with width 6cm and 3cm. Is my logic right?
My code:
library(kableExtra)
library(xtable)
df = mtcars[1:5,1:4]
df = xtable(df)
align(df) = c("l","l","r","r","r")
df %>% xtable2kable(include.rownames=FALSE) %>% column_spec(1, width = "6cm") %>% column_spec(2, width = "3cm") %>%
column_spec(3, width = "3cm") %>% column_spec(4, width = "2cm") %>% row_spec(0, bold = T, color = "white", background = "#2F2E41")
df = mtcars[1:5,c(1,3,4)]
df = xtable(df)
align(df) = c("l","l","r","r")
df %>% xtable2kable(include.rownames=FALSE) %>% column_spec(1, width = "9cm") %>%
column_spec(2, width = "3cm") %>% column_spec(3, width = "2cm") %>% row_spec(0, bold = T, color = "white", background = "#2F2E41")
Ofc I can manually set up the width until the tables are perfectly aligned. Or is there a better method to solve the problem?
Thank you in advance!
In LaTeX, there's a separation between each column as well as a width. The size of the separation is in \tabcolsep
. When you have more columns you get more separators, and so a wider table overall.
You could fix this problem by setting the separation to zero, e.g. putting this LaTeX code early in your document:
\setlength{\tabcolsep}{0pt}
In LaTeX I think you could also set the width of the wide column to 9cm plus \tabcolsep
so you keep the separation in other places, but I'm not sure if kableExtra
supports that.
Edited to add:
This seems to work without modifying \tabcolsep
: create a new length including it (actually twice, you get the separation on both sides), and use that. You'd put code like this early in the document
\newlength{\widecolsize}
\setlength{\widecolsize}{9cm}
\addtolength{\widecolsize}{2.0\tabcolsep}
and then produce the table using this code:
df %>% xtable2kable(include.rownames=FALSE) %>% column_spec(1, width = "\\\\widecolsize") %>%
column_spec(2, width = "3cm") %>% column_spec(3, width = "2cm") %>% row_spec(0, bold = T, color = "white", background = "#2F2E41")