I would like to keep just the "inside" lines of a latex table created by kable. I only know cumbersome and ugly ways to do so...attempts at cleaner versions failed. here is one clean flunk:
kable.rewrap <- function( df, newname= "mytable" ) {
kt <- kable( df, "latex", booktabs=T )
notop <- strsplit(kt, "\\midrule")[[1]][2]
nosur <- strsplit(notop, "\\bottomrule" )[[1]][1] ## fails: doesn't like "\\"!
newkt <- paste0("\\begin{", newname, "}", nosur, "\n\\end{",newname,"}\n")
## attr(newkt, "format") <- chr "latex" # wrong
newkt
}
print(kable.rewrap( data.frame( x=1:3, y=1:3 ), "mytable" ))
should produce
\begin{mytable}
\toprule
x & y\\
\midrule
1 & 1\\
2 & 2\\
3 & 3\\
\bottomrule
\end{mytable}
obviously, my latex code should define an environment mytable
now. I am also puzzled by "bottomrule" in the nosur
line works, but "\\bottomrule" fails.
(another alternative is to forego kable altogether and just work with the data frame, separating each line by a \ and each column by a &.)
advice appreciated.
1) The kable.envir
argument will add the mytable
part but that still causes tabulars to be generated which we remove using gsub
:
kable(test_data, "latex", booktabs = TRUE, table.envir = "mytable") %>%
gsub(".(begin|end){tabular.*}", "", ., perl = TRUE)
giving:
\begin{mytable}
\toprule
x & y\\
\midrule
1 & 1\\
2 & 2\\
3 & 3\\
\bottomrule
\end{mytable}
2) Another possibility is to define your own mytabular environment and then use:
kable(test_data, "latex", booktabs = TRUE, table.envir = "mytable") %>%
kable_styling(latex_table_env = "mytabular")
which gives:
\begin{mytable}
\begin{mytabular}{rr}
\toprule
x & y\\
\midrule
1 & 1\\
2 & 2\\
3 & 3\\
\bottomrule
\end{mytabular}
\end{mytable}
In (2) rather than defining a do-nothing environment to replace tabular tex/latex actually makes one available already, namely @empty
.
kable(test_data, "latex", booktabs = TRUE, table.envir = "mytable") %>%
kable_styling(latex_table_env = "@empty")
We named the data frame shown in the question as follows:
test_data <- data.frame(x = 1:3, y = 1:3)