r - Rmarkdown docx中的flextable不在if语句中打印如果其他文本
问题描述
我正在尝试使用该包flextable
在我的 Rmarkdown 中获取一些格式良好的表格(转到 word 文件)。这些表通常工作得很好,但如果我把它放在 if 语句中,如果从 if 语句中打印了其他任何内容,我看不到表。有什么想法吗?
为仍在关注此内容的任何人更新 2020 年 1 月
从 flextable 的 0.5.5 版开始,有一个新功能docx_value
可以解决这个问题,我已经更新了答案以反映这一点,这样其他人就不会使用复杂的解决方法,现在有一个简单的解决方案。
我的例子(一起运行):
---
title: "Testing"
output:
word_document:
reference_docx: styles.docx
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
```{r defaults}
library(pander)
library(knitr)
library(flextable)
```
第一次测试工作正常 - 没有 if 语句和表格两侧的新行
## test 1 table no if statemnets
```{r test1, echo = FALSE, results = 'asis'}
test <- data.frame (c = 1:5, x = 6:10)
testft <- flextable(test)
testft
```
第二个测试有一个没有其他文本的 if 语句并且工作正常
## test 2 if statement no other text
```{r test2, echo = FALSE, results = 'asis'}
RunTable <- TRUE
if(RunTable){
testft
}
```
但是,如果我尝试在 if 语句中添加其他输出,无论有没有换行符,我的输出中都没有任何表格
## test 3 if statement with other text
```{r test3, echo = FALSE, results = 'asis'}
#Hack so dat works up to year 2047 as cpp functions in padr can't handle data beyond 2038
#Get Daily Values
RunTable <- TRUE
if(RunTable){
print("before ")
testft
print("after ")
}
```
## test 4 if statement with other text and newlines
```{r test4, echo = FALSE, results = 'asis'}
RunTable <- TRUE
if(RunTable){
print("if with linebreak before ")
cat(" \n")
knit_print(testft)
cat(" \n")
print("if with linebreak after ")
}
```
解决方案
您可以使用 chunk 选项并使用如下方式results = 'asis'
编写 openxml 内容format
## test 4 if statement with other text and newlines
```{r test4, echo = FALSE, results = 'asis'}
RunTable <- TRUE
if(RunTable){
print("if with linebreak before ")
cat(" \n")
cat(
paste(
"\n```{=openxml}",
format(testft, type = "docx"),
"```\n", sep = "\n")
)
cat(" \n")
print("if with linebreak after ")
}
```
推荐阅读
- php - 如何在此处添加按日期排序?
- r - 通过匹配字符串分隔列
- oracle - 有没有更快的方法在 oracle pl/sql 中每周对 120k 条记录执行合并?
- nginx - 如何修复此 NGINX 502 Bad Gateway 错误?
- push-notification - Firebase Cloud Messaging - 识别特定推送通知消息的传递状态
- html - 如何强制横幅在 CSS 中放大并全宽?
- spring-boot - 当我们在 restfull web 服务中有多层服务调用方法时如何使用 junit 和 mockito
- arduino - 用arduino自动发送短信?
- r - 在R中的索引上组合列表
- python - sorted(file.read().split()) 不给出排序结果