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

I presume your problem is related to this issue. Changing the problematic chunks like this seems to work:

## test 3 if statement with other text

```{r test3, echo = FALSE}
RunTable <- TRUE
if(RunTable){
  text <- c(
    "before   ",
    knit_print(testft),
    "after   "
  )

  asis_output(paste(text, collapse = "\n"))
}
```

## test 4 if statement with other text and newlines

```{r test4, echo = FALSE}
RunTable <- TRUE
if(RunTable){
  text <- c(
    "if with linebreak before   ",
    "  \\newline",
    knit_print(testft),
    "  \\newline\n",
    "if with linebreak after   "
  )

  asis_output(paste(text, collapse = "\n"))
}
```

Regarding the last one:

  • I had to use \\newline to actually insert an extra blank line before the table.
  • I don't know why an extra \n is needed for the blank line after, it wouldn't work for me otherwise.
  • Just to test, I tried adding several \\newline entries, both before and after, but one blank line was the most I could get.

You can use chunk option results = 'asis' and write the openxml content with format as following

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

```

Not sure if you would consider a different package, but this seems to work:

---
title: "Testing"
output: 
  word_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.height=1.5, fig.width=3, fig.align='right', fig.align = "center")
```

## R Markdown

```{r defaults}
library(pander)
library(knitr)
library(flextable)
library(tableHTML)

```


## test 1 table no if statemnets

```{r test1, echo = FALSE}

  test <- data.frame (c = 1:5, x = 6:10)
  tab <- tableHTML(test, widths = c(60, 60), rownames = FALSE) %>% add_theme('scientific')

  tab %>% tableHTML_to_image()

```

## test 2 if statement no other text

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

  tab %>% tableHTML_to_image()

}

```


```{r test3, echo = FALSE}
#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   ")

  tab %>% tableHTML_to_image()

  print("after   ")

}

```

## test 4 if statement with other text and newlines


```{r test4, echo = FALSE}
RunTable <- TRUE
if(RunTable){

  print("if with linebreak before   ")
  cat("  \n")

  tab %>% tableHTML_to_image()

  cat("  \n")

  print("if with linebreak after   ")


}

For example, you can see test 4 as an output:

enter image description here

A couple of notes:

  • You can format the table in the exact way you want.
  • The code produces an image.