Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to use the package flextable 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?


Update Jan 2020 for any people still looking at this

As of version 0.5.5 of flextable there is a new function docx_value to address this, I have updated the answer to reflect this so that other people don't use the complicated workarounds now there is a simple solution.


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

like image 618
Sarah Avatar asked May 31 '19 03:05

Sarah


1 Answers

Update Jan 2020 for any people still looking at this

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.
like image 110
Sarah Avatar answered Oct 01 '22 01:10

Sarah