Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
949 views
in Technique[技术] by (71.8m points)

latex - R: why kable doesn't print inside a for loop?

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.

This is my code:

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

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

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?

### EDIT ###

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...