xtable in .Rmd then knit as pdf in rstudio shows %

2019-04-24 08:43发布

问题:

I am making a PDF using Rstudio's 'knit PDF' option when writing an R Markdown (.Rmd) file.

When creating a table using the xtable function, text commented in latex using the % is displayed in the pdf. This problem goes away when knitting a .Rnw file using latex and R.

Below the is an example of an .Rmd file to be knitted as PDF and the equivalent .Rnw file, to knitted (as pdf, naturally).

Their PDF results are identical, except for one line. Just above the table, the following is displayed:

% latex table generated in R 3.1.0 by xtable 1.7-3 package % Wed Aug 06 19:06:37 2014

MarkdownFile.Rmd

---
output: pdf_document
---

```{r, results='asis'}
library(xtable)
xtable(summary(cars)) 
```

SweaveFile.Rnw

\documentclass{article}

\begin{document}

<<r, results='asis'>>=
library(xtable)
xtable(summary(cars))
@

\end{document}

The actual output of the xtable(summary(cars)) expression in r is as below. You can see the first two lines, starting with % The difference is that .Rnw file hides them and .Rmd files do not.

% latex table generated in R 3.1.0 by xtable 1.7-3 package
% Wed Aug 06 19:33:18 2014
\begin{table}[ht]
\centering
\begin{tabular}{rll}
\hline
 &     speed &      dist \\ 
  \hline
1 & Min.   : 4.0   & Min.   :  2.00   \\ 
  2 & 1st Qu.:12.0   & 1st Qu.: 26.00   \\ 
  3 & Median :15.0   & Median : 36.00   \\ 
  4 & Mean   :15.4   & Mean   : 42.98   \\ 
  5 & 3rd Qu.:19.0   & 3rd Qu.: 56.00   \\ 
  6 & Max.   :25.0   & Max.   :120.00   \\ 
   \hline
\end{tabular}
\end{table}

I am assuming that the problem is that the knitted .Rmd file doesn't recognise the % as a latex comment and thus prints it. How can I get rid of these lines above my table? is there a way for .Rmd files to recognise the % as comment?

回答1:

As @celiomsj said, use the comment argument to print.xtable and set it to FALSE to omit the arguments:

print(xtable(summary(cars)), comment=FALSE)