rr-markdownr-flextable

flextable in Rmarkdown docx not printing within if statement if other text


I'm trying to use the Flextable package to get some nicely formatted tables in my Rmarkdown (going to word file). The tables work just fine in general but if I put it within an if statement, if there is anything else being printed from the if statement I don't see the table. Any ideas what's going on?

My example (run all together):

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

```

1st test works fine - no if statement and new lines either side of table

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

```

2nd test has an if statement with no other text and works fine

## test 2 if statement no other text

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

  testft

}

```

But if I try and add other outputs in my if statement, either with or without new line breaks I don't get any table in my output

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


}

```

Output: My output


Solution

  • As of version 0.5.5 of flextable there is a new function docx_value to address this, as described in the package news:

    flextable 0.5.5

    new features

    • new function docx_value to let display flextables from non top level calls inside R Markdown document.