Rmarkdown docx中的flextable无法在if语句中打印if其他文本

Sar*_*rah 12 r flextable r-markdown

我正在尝试使用该程序包flextable在Rmarkdown中获取一些格式正确的表(转到Word文件)。这些表通常工作正常,但是如果我将其放在if语句中,则如果if语句中还有其他内容在打印,则看不到该表。有什么想法吗?

我的例子(一起运行):

---
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)

```
Run Code Online (Sandbox Code Playgroud)

第一个测试工作正常-否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

```
Run Code Online (Sandbox Code Playgroud)

第二个测试有一个if语句,没有其他文本,可以正常工作

## test 2 if statement no other text

```{r test2, echo = FALSE, results = 'asis'}
RunTable <- TRUE
if(RunTable){

  testft

}

```
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试在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   ")


}

```
Run Code Online (Sandbox Code Playgroud)

输出: 我的输出

Sar*_*rah 1

2020 年 1 月更新,供仍在关注此内容的人使用

从 flextable 0.5.5 版本开始,有一个新函数docx_value可以解决这个问题,如包新闻中所述:

灵活0.5.5

新功能

  • 新函数docx_value可以让 R Markdown 文档中的非顶级调用显示弹性表。