rformattingknitrtexkable

Remove the table environment using kable (from R dataframe to TeX)


Hello suppose I have my dataframe as:

a <- data.frame("column 1" = letters[1:5], "column 2" = letters[6:10], "column 3" = rnorm(5))

I use kable to produce a TeX table

> kable(a, 'latex', booktabs = T, linesep = "", col.names = NULL)

\begin{tabular}{llr}
\toprule
a & f & -0.4681726\\
b & g & 0.0122811\\
c & h & 0.3477899\\
d & i & 0.9131300\\
e & j & 1.0050357\\
\bottomrule
\end{tabular}

I was looking into the documentation, and GPT but couldn't find an answer on removing the following lines. (I think that in Stata is with the esttab and fragment option)

\begin{tabular}{llr}
\toprule

\bottomrule
\end{tabular}

This is the desired output:

a & f & -0.4681726\\
b & g & 0.0122811\\
c & h & 0.3477899\\
d & i & 0.9131300\\
e & j & 1.0050357\\

I tried to do with gsub as:

a <- gsub("\\\\begin\\{tabular\\}\\{llr\\}\n\\\\toprule", "", a)
a <- gsub("\\\\bottomrule\n\\\\end\\{tabular\\}","", a)

But if my dataframe is slightly different (more or fewer columns) the first line does not apply.

How can I achieve this in a more general way?

Thanks in advance!


Solution

  • I would use xtable:

    library(xtable)
    latex <- xtable(a)
    print(latex, 
          only.contents = T, # what you desire
          include.rownames = F, 
          include.colnames = F,
          hline.after = NULL, # no horizontal lines
          comment = F) # do not print timestamp and message
    

    Producing:

      a & f & -0.69 \\ 
      b & g & 0.35 \\ 
      c & h & -0.40 \\ 
      d & i & -1.33 \\ 
      e & j & 2.71 \\
    

    Optionally use file = "yourfile.tex" to write the table to file.