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

查看:17
本文介绍了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 knitr print in a loop 为重复的答案.不是,因为正如我在上一段中所说,这有效地打印了表格,但格式不是预期的.接受的答案(和相关的 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

你只需要在每次打印调用后换行

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("
")
}
```

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

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