首页 > 解决方案 > 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   ")


}

```

输出: 我的输出

标签: rr-markdownflextable

解决方案


您可以使用 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   ")
}

```

推荐阅读