[Tex/LaTex] knitR, XeLaTeX and tikz in RStudio: fails to compile

knitrrstudiotikz-pgfxetex

I try to use knitr, tikz and xelatex in RStudio.
Minimum Example:

%-*- program: xelatex -*- 
% !Rnw weave = knitr
\documentclass{article}
\usepackage[a4paper]{geometry}

\usepackage{fontspec}
\usepackage{tikz}

\begin{document}
<<test, dev='tikz'>>= 
plot(1) 
@

Add some text äöüäöü
\end{document}

If I compile as is, I get "Error: failed to compile figure/test-1.tikz to PDF".

If I remove fontspec, it compiles fine but does not display öäüöäü.

If I remove the R-code, it compiles fine with öäüöäü.

sessionInfo()
## R version 3.3.1 (2016-06-21)
## Platform: x86_64-apple-darwin13.4.0 (64-bit)
## Running under: OS X 10.11.6 (El Capitan)
##
## locale:
## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
##
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base
##
## other attached packages:
## [1] knitr_1.14
##
## loaded via a namespace (and not attached):
## [1] magrittr_1.5      formatR_1.4       tools_3.3.1
## [5] filehash_2.3      stringi_1.1.1     grid_3.3.1
## [9] evaluate_0.9

Thanks for any help.

Best Answer

OK, I found the solution:

Add the lines

<<pre_load>>=
options(tikzDefaultEngine='xetex')
@

right after

\begin{document}

and make sure it is not cached. Why this is only needed with fontspec escapes me.

Related Question