微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Latex for 循环中使用 R 内联代码

如何解决在 Latex for 循环中使用 R 内联代码

我有一个包含 Latex 表蓝图的 R markdown 文件。在那个表中,我想将数据帧中的数据放入 R 中。使用 'r [R code]' 我可以做到这一点。这仅对静态表有用。

有没有办法在不使用此符号或其某些变体的数据帧中进行迭代?

我基本上想将数据从具有不同行数的数据帧 df 复制到 Latex 表中。

Sth like this: 

```
\begin{table}
[Latex code]

For (y in 1:n){
'r df[j,1]` & `r df[j,2]`}

[Latex code]
\end{table}
```

这可能吗? 这是当前静态版本与我想要的样子的代码示例:

/// R script that creates data
```
data <- data.frame (c(10,20,30),c("first","second","third"))
colnames(data) <- c("Col1","Col2")
save (data,file = "data.RData")
```

/// in R markdown:
  
```  
title: "dynamicmarkdown"
output: pdf_document
header-includes:
- \usepackage{booktabs}
- \usepackage[utf8]{inputenc}
- \usepackage{graphicx}
- \usepackage[ngerman]{babel}
- \usepackage{lastpage}
- \usepackage{hyperref}
- \usepackage{fancyhdr}
- \usepackage{placeins}
---
  
<!-- load data -->
```{r echo = FALSE}
dfx <-load("data.RData")
df <- data
```
```
\begin{center}
\end{center}
$\ \\$
$\ \\$
$\ \\$
$\ \\$
$\ \\$
$\ \\$
\begin{table}[!h]
\centering
\begin{tabular}{ |c|c|c|c|} 
\hline
$\textbf{Col1}$ & $\textbf{Col2}$ \\ 
\midrule[1pt]
\specialrule{2pt}{-2pt}{-2pt} 
\specialrule{2pt}{0pt}{0.5pt}
`r df[[1,1]]` & `r df[[1,2]]` \\ \hline
`r df[[2,1]]` & `r df[[2,2]]` \\ \hline 
`r df[[3,1]]` & `r df[[3,2]]` \\ \hline
\end{tabular}
\end{table}
```



/// I want to do it this way:

```
title: "dynamicmarkdown"
output: pdf_document
header-includes:
- \usepackage{booktabs}
- \usepackage[utf8]{inputenc}
- \usepackage{graphicx}
- \usepackage[ngerman]{babel}
- \usepackage{lastpage}
- \usepackage{hyperref}
- \usepackage{fancyhdr}
- \usepackage{placeins}
---
  
<!-- load data -->
```{r echo = FALSE}
dfx <-load("data.RData")
df <- data
```

```
\begin{center}
\end{center}
$\ \\$
$\ \\$
$\ \\$
$\ \\$
$\ \\$
$\ \\$
\begin{table}[!h]
\centering
\begin{tabular}{ |c|c|c|c|} 
\hline
$\textbf{Col1}$ & $\textbf{Col2}$ \\ 
\midrule[1pt]
\specialrule{2pt}{-2pt}{-2pt} 
\specialrule{2pt}{0pt}{0.5pt}
j = 1
for ( j in 1:nrows(df)){
`r df[[j,1]]` & `r df[[j,2]]` \\ \hline}
\end{tabular}
\end{table}  
```

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。