Sophie Wupper
Sophie Wupper

Reputation: 35

RMarkdown Officedown: Loop over child document containing flextable with UTF-8 encoding

Is it possible to include a child document in a loop that contains a flextable with UTF-8 encoding?

This is my YAML:

---
output: officedown::rdocx_document
---

Without using a loop, it works perfectly and the Delta ("\U0394") is displayed correctly in the output file:

```{r, echo = FALSE, message = FALSE}
library(flextable)

# Create columns
col1 <- c("a", "\U0394")
col2 <- c(1.0, 2.0)

# Create dataframe
data <- data.frame(Parameter = col1,
                   Value = col2)

# Create flextable
ft <- flextable(data)
ft
```

To loop over this flextable, I saved the code above as a child file and included it in an asis-chunk with knit_child()...

```{r, echo = FALSE, message = FALSE, results = "asis"}
library(rmarkdown)
library(knitr)
library(flextable)

# Read child doc two times
for (i in 1:2){
  out <- knit_child("path_to_child\\child.Rmd", quiet = TRUE)
  cat(out)
  cat("\n\n")
}
```

...but then get this error, because the UTF-8 encoding is somehow not recognized anymore:

Error in read_xml.character(file) : error parsing attribute name [68]

Upvotes: 0

Views: 346

Answers (2)

M. white
M. white

Reputation: 80

I had the same experience using "\u226570" inside a loop. It is due to the aspects of your system locale. Follow this:

  1. Use sessionInfo() and check the locale information.
  2. Change locale to English_United States.utf8 or other utf8 styles (like en_GB.UTF-8) if they are not already set. You can do this using Sys.setlocale("LC_ALL","English_United States.utf8").
  3. Check session information again and if locale settings are still unchanged, probably your OS does not support UTF-8 (e.g, updated versions of Windows have better UTF-8 support).

I think your problem would be resolved after setting a valid UTF-8 locale.

Upvotes: 1

David Gohel
David Gohel

Reputation: 10675

You need to use flextable_to_rmd.

See:

You have to slightly adjust the code in "path_to_child/child.Rmd":



```{r, echo = FALSE, message = FALSE, results='asis'}
library(flextable)

# Create columns
col1 <- c("a", "\U0394")
col2 <- c(1.0, 2.0)

# Create dataframe
data <- data.frame(Parameter = col1,
                   Value = col2)

# Create flextable
ft <- flextable(data)

flextable_to_rmd(ft)
```

Upvotes: 0

Related Questions