如何在rmd文件中使用循环编织knit_print flextable [英] How to knit_print flextable with loop in a rmd file
问题描述
我正在尝试使用 flextable 和 kable 软件包生成多张表.当我想迭代输出某些表时,我发现flextable的knit_print
在循环中不起作用.下面是一个最小的示例:
I am trying to produce mutltiple tables using the flextable and kable packages. When I want to output some table iteratively, I found knit_print
of flextable is not working in loop. Below is a minimal example:
---
output: word_document
---
```{r}
library(flextable)
library(knitr)
```
```{r}
data(cars)
speed<-unique(cars$speed)
for (v in 1:length(speed)) {
carspd<-cars[which(cars$speed==speed[v]),]
tb<-regulartable(carspd)
knit_print(tb)
}
knit_print(tb)
```
最后一个knit_print
可以将结果打印到带有.Rmd
文件的word_document中.
Just the last knit_print
can print the result to the word_document with the .Rmd
file.
现在,我发现在.md
中它们之间的区别,它是由带有superedit的pandoc进程文件输出的,
右表:
Now I find the difference of them in .md
which is output by the pandoc process file with ultraedit,
the right table:
```{=openxml}
<w:tbl xmlns:w=".......
错误的表:
鈥媊``{=openxml}
<w:tbl xmlns:w="
在十六进制中有多余的内容:"E2 80 8B",有人称它们为零宽度空间吗?但是我不知道如何避免.
In hexadecimal there are extra content:"E2 80 8B", someone call they Zero-Width Space? But I am not figure out how to avoid it.
推荐答案
这是flextable
在其knit_print
方法中使用的功能之一的限制:knitr::asis_output()
不能在循环中使用.这里介绍了几种解决方案: https://github.com/yihui/knitr/issues/1137 .
This is a limitation of one of the functions that flextable
uses in its knit_print
method: knitr::asis_output()
can't be used in a loop. A couple of solutions are described here: https://github.com/yihui/knitr/issues/1137.
这个在HTML输出中对我有用,只是将所有输出收集到一个大向量中并在最后打印出来.我修改了代码,在表格之前也插入了一些文本,并在表格之后插入了一个数字. 我不使用Word,但我认为它也可以在其中工作:
This one works for me in HTML output, just collecting all the output into one big vector and printing it at the end. I have modified the code to also insert some text before the table and a figure after it. I don't use Word, but I'd assume it will also work there:
---
output: html_document
---
```{r}
library(flextable)
library(knitr)
```
```{r}
data(cars)
speed <- unique(cars$speed)
results <- character()
for (v in 1:length(speed)) {
carspd <- cars[which(cars$speed == speed[v]),]
tb <- regulartable(carspd)
# Generate a figure in a temporary file
filename <- tempfile(fileext = ".png")
png(filename)
hist(carspd$dist)
dev.off()
# Put everything into the results vector
results <- c(results, "\n\nThis is the table for v =", v,
knit_print(tb),
knitr:::wrap(include_graphics(filename)))
}
asis_output(results)
knit_print(tb)
```
一些注意事项:
- 文本中的
\n\n
似乎是插入换行符所必需的. -
knitr:::wrap()
函数是knitr
中未记录的内部函数,因此可能存在我不知道的限制,并且在knitr
的某些将来版本中可能会失败.
- The
\n\n
in the text seems to be necessary to insert a line break. - The
knitr:::wrap()
function is an undocumented internal function inknitr
, so there might be limitations that I don't know about, and this might fail in some future version ofknitr
.
这篇关于如何在rmd文件中使用循环编织knit_print flextable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!