R:为什么kable不会在for循环中打印? [英] R: why kable doesn't print inside a for loop?

查看:190
本文介绍了R:为什么kable不会在for循环中打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用rmarkdown和Latex制作报告.我需要使用knitr::kable打印一组表,但是在for循环中不打印.

I'm working a report with rmarkdown and latex. I need to print a group of tables using knitr::kable, but the don't print when inside a for loop.

这是我的代码:

---
title: "project title"
author: "Mr. Author"
date: "2016-08-30"
output: 
  pdf_document: 
    latex_engine: xelatex
bibliography: biblio.bib
header-includes:
   - \usepackage{tcolorbox}
---

Text and chunks that run ok.

```{r loadLibraries}
require(data.table)
require(knitr)
```

## Try to print a group of tables from split

```{r results = "asis"}
t1 <- data.table(a = sample(letters, 10, T), b = sample(LETTERS[1:3], 10, T))
t2 <- split(t1, t1$b)

for (i in 1:length(t2)){
    kable(t2[[i]], col.names = c("A", "B"))
}
```

是否使用results = "asis"或完全省略它都没有关系,什么都不会打印到文档上.

It doesn't matter if I use results = "asis" or if I omit it altogether, nothing prints to the document.

我尝试将kable调用包含在print调用(print(kable(t2[[i]]...)中,并且它成功将输出打印到文档中,但是格式与标准R提示符的格式相同(前面有##),这很丑陋.

I've tried enclosing the kable call within a print call (print(kable(t2[[i]]...), and it successfully prints the output to the document, but the format is the same format as a standard R prompt (preceded by ##, for example), which is rather ugly.

除了手动之外,如何显示表格?

How can I display the tables, other than manually?

###编辑###

一些回答者已将我重定向到 R编织成环状重复的答案. 不是,因为正如我在上一段中所述,这有效地打印了表格,但格式不是预期的格式.接受的答案(和相关的github线程)确实解决了问题.

Some answerers have redirected me to R knitr print in a loop as a duplicate answer. It's not, because as I stated in the previous paragraph, this effectively prints the table, but the format is not the expected one. The accepted answer (and related github thread) really solved the problem.

推荐答案

此问题在此处得到解决: https://github.com/yihui/knitr/issues/886

This question is addressed here: https://github.com/yihui/knitr/issues/886

您需要做的是在每次打印呼叫后换行

All you need is a line break after each print call

---
title: "project title"
author: "Mr. Author"
date: "2016-08-30"
output: 
  pdf_document: 
    latex_engine: xelatex
    bibliography: biblio.bib
    header-includes:
       - \usepackage{tcolorbox}
---

Text and chunks that run ok.

```{r loadLibraries}
require(data.table)
require(knitr)
```

```{r results = "asis"}
t1 <- data.table(a = sample(letters, 10, T), b = sample(LETTERS[1:3], 10, T))
t2 <- split(t1, t1$b)

for (i in 1:length(t2)){
    print(kable(t2[[i]], col.names = c("A", "B")))
    cat("\n")
}
```

这篇关于R:为什么kable不会在for循环中打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆