简体   繁体   English

通过R markdown和knitr加载并打印新页面中的每个表

[英]Load and print every table in new page by R markdown and knitr

I have about 60 .Rdata files in the same directory. 我在同一目录中大约有60个.Rdata文件。 The object name in all those .Rdata are same. 所有这些.Rdata中的对象名称都相同。 I want to write some code to load and print all 60 .Rdata file and each file in the new page. 我想编写一些代码来加载和打印所有60个.Rdata文件以及新页面中的每个文件。 For example, if the file name is file_1.rdata , file_2.rdata and file_3.rdata . 例如,如果文件名是file_1.rdatafile_2.rdatafile_3.rdata The object name in all three .Rdata files is table . 所有三个.Rdata文件中的对象名称均为table The following knitr code showed exactly what I want, 以下编织代码完全显示了我想要的内容,

>\```{r,echo=FALSE}  
>load("file_1.rdata")  
>print(table)  
>\```  
>\pagebreak  
>\```{r,echo=FALSE}  
>load("file_2.rdata")  
>print(table)  
>\```  
>\pagebreak  
>\```{r,echo=FALSE}  
>load("file_3.rdata")  
>print(table)  
>```  
>\pagebreak

But I have more than 60 files, it is really hard to write all the code by hand. 但是我有60多个文件,手工编写所有代码真的很困难。 I can write for loop in R block, however, how can I make a new page for each .rdata file? 我可以在R块中编写for循环,但是,如何为每个.rdata文件创建一个新页面?

The for loop will be for循环将是

>\```{r,echo=FALSE}  
>names <- c("file_1.rdata","file_2.rdata","file_3.rdata")  
>for(i in 1:length(names)){  
>  current_object <- names[i]  
>   load(current_object)  
>  print(table)  
>}  
>\```  

You can try adding in cat("\\n\\n\\\\pagebreak\\n") inside your for loop, and results='asis' to your chunk call: 您可以尝试在for循环中添加cat("\\n\\n\\\\pagebreak\\n") ,然后在块调用中添加results='asis'

```{r,echo=FALSE, results='asis'}

names <- c("file_1.rdata","file_2.rdata","file_3.rdata")
for(i in 1:length(names)){
   current_object <- names[i]
   load(current_object)
   print(table)
   cat("\n\n\\pagebreak\n")
}

```

It works for me with mtcars: 它适用于mtcars:

---
title: "test"
output: pdf_document
---

```{r, echo=FALSE, results='asis'}
for (i in 1:3) {
  print(mtcars)
  cat("\n\n\\pagebreak\n")
}
```

NB you might want to look into the function kable to format your tables more nicely. 注意,您可能想研究一下函数kable以更好地格式化表格。 Or using library(xtable) : 或者使用library(xtable)

```{r, echo=FALSE, results='asis'}
for (i in 1:3) {
  print(xtable::xtable(mtcars), type = "latex")
  cat("\n\n\\pagebreak\n")
}
```

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM