在 Rstudio 中生成 LaTeX 表格而不是文本

Generating LaTeX tables instead of text in Rstudio

我是乳胶新手,想生成 PDF tables 而不是文本,所以我的例子是:

在我的 METHOD.tex 文件中我有这样的文本:

在第一组中有:AAA:项目:BBB:项目 2 和:CCC:项目 3。我们评估了:EEE:实施。总数中:VVV:回复前反对调查:X111:,拒绝:X222

所以 AAA, BBB, CCC.. 是我存储数字的对象。

a1<-200
b1<-450
c1<-500
d1<-1500

所以现在我使用了这个代码:

df<-data.frame(AAA,BBB,CCC,EEE)

比我写的:

df <- scan("METHOD.tex", character(0), sep="\n", quiet=TRUE, encoding="UTF-8")

并使用了以下代码(因为我正在生成更多不同的报告并且数字在变化):

df <- gsub(pattern=":AAA:", replacement=a1, x=df)
df <- gsub(pattern=":BBB:", replacement=b1, x=df)
...

最后我用了这个:

df<- capture.output(Hmisc::latex(df, caption="Table", rowlabel="", file="", where="H"))

但是当我想生成 table 而不是文本时,什么也没有发生。还有AAA、BBB、CCC。 所以我在代码的最后部分遗漏了一些东西。

R Studio 中的 R markdown 使这类事情变得更好。 R 代码块可以用三个反引号 {r}code 声明,然后用一个反引号和 r.

声明内联代码

下面的操作与您想要的类似。

---
title: "Untitled"
author: "user"
date: "Tuesday, May 05, 2015"
output: 
  pdf_document:
    keep_tex: true
---

```{r}
require(xtable)
a1<-200
b1<-450
c1<-500
d1<-1500
```

In the first group there were: `r a1` items: `r b1` items2 and: `r c1` items3. We assessed: EEE: implementations. Of the total: VVV: objects to the survey before replying: X111 :, rejected: X222

```{r, results='asis', echo = FALSE}
data(mtcars)
out <- xtable(head(mtcars), caption = "Head of mtcars data set", label = "mt_head")
print(out, comment = FALSE)
```

这会将以下输出生成到 tex 文件中

% Excised preamble
\begin{document}
% Excised ECHO 
In the first group there were: 200 items: 450 items2 and: 500 items3. We
assessed: EEE: implementations. Of the total: VVV: objects to the survey
before replying: X111 :, rejected: X222

\begin{table}[ht]
\centering
\begin{tabular}{rrrrrrrrrrrr}
  \hline
 & mpg & cyl & disp & hp & drat & wt & qsec & vs & am & gear & carb \ 
  \hline
Mazda RX4 & 21.00 & 6.00 & 160.00 & 110.00 & 3.90 & 2.62 & 16.46 & 0.00 & 1.00 & 4.00 & 4.00 \ 
  Mazda RX4 Wag & 21.00 & 6.00 & 160.00 & 110.00 & 3.90 & 2.88 & 17.02 & 0.00 & 1.00 & 4.00 & 4.00 \ 
  Datsun 710 & 22.80 & 4.00 & 108.00 & 93.00 & 3.85 & 2.32 & 18.61 & 1.00 & 1.00 & 4.00 & 1.00 \ 
  Hornet 4 Drive & 21.40 & 6.00 & 258.00 & 110.00 & 3.08 & 3.21 & 19.44 & 1.00 & 0.00 & 3.00 & 1.00 \ 
  Hornet Sportabout & 18.70 & 8.00 & 360.00 & 175.00 & 3.15 & 3.44 & 17.02 & 0.00 & 0.00 & 3.00 & 2.00 \ 
  Valiant & 18.10 & 6.00 & 225.00 & 105.00 & 2.76 & 3.46 & 20.22 & 1.00 & 0.00 & 3.00 & 1.00 \ 
   \hline
\end{tabular}
\caption{Head of mtcars data set} 
\label{mt_head}
\end{table}

\end{document}

并自动从tex文件编译成pdf。