使用 knitr 将类/包/主题选项传递给 R

使用 knitr 将类/包/主题选项传递给 R

我有一个beamer包含块的文档R,例如“template.Rnw”,我用它来编译knitr使用“编译 PDF”对其进行编译RStudio。我已定义了一个主题“mytheme.sty”。我希望为该主题添加一个选项French,并在文档顶部这样调用它:

    \usetheme[French]{mytheme}

此“法国”主题定义了与美国风格不同的图形的标签格式选项,例如$1,000,000.00打印为1 000 000,00$

我认为我可以在“mytheme.sty”中创建一个布尔值French == 1,然后将其传递给R块以供条件使用if (French) { # set the French styles here

但是,首先,我不知道如何将LaTeX计数器值(比如说)传递给R块。此外,也许还有更好的方法。如果有的话,我很想知道。以下是我的 MWE(警告:无法编译!)

模板.Rnw

\documentclass{beamer}
\usetheme{mytheme}
%\usetheme[French]{mytheme}

<<'setup', include=FALSE>>=
library(knitr)
library(ggplot2)
library(scales)
@

% I'd want to hide this chunk inside mytheme.sty or similar
<<'formats', include=FALSE>>=
# Create euro currency symbol in plot labels with library(scales)
euro <- function(x) {
paste0("€", format(x, big.mark = ",", decimal.mark = ".", trim = TRUE,
    scientific = FALSE))
} 
# French style formatting for euro labels
euroFrench <- function(x) {
paste0(format(x, big.mark = " ", decimal.mark = ",", trim = TRUE,
    scientific = FALSE), " €")
} 
# French style formatting for dollar labels
dollarFrench <- function(x) {
paste0(format(x, big.mark = " ", decimal.mark = ",", trim = TRUE,
    scientific = FALSE), " $")
} 
#  Toggle On/Off to set formats to French or US
if (French) {  # Here reads the boolean French set by the option [French]
  euro <- euroFrench      # set the custom 'euro' style to custom 'euroFrench'
  dollar <- dollarFrench  # overwrite the default 'dollar' styles of library(scales)
}
@

\begin{document}
\begin{frame}
\frametitle{One day I will be a dual-axis euro/dollar plot}
<<'plot', out.width='1\\linewidth'>>=
df <- data.frame(x = c(0, .0001, .0002, .0003), y = c(0, 1000000, 2000000, 3000000))
ggplot(data = df, aes(x = x, y = y)) + geom_line() + theme_classic(30) + scale_x_continuous(labels = dollar) + scale_y_continuous(labels = euro)
@
\end{frame}
\end{document}

mytheme.sty

\newcounter{French}
\newif\if@themeFrench%
\@themeFrenchfalse%
\DeclareOption{French}{\@themeFrenchtrue}%
\ProcessOptions%
\if@themeFrench% 
\setcounter{French}{1}
@
\fi

阴谋R在课外 获得beamer

在此处输入图片描述

答案1

没有办法(至少不是直接的方法)将 LaTeX 变量传递给 R。相反的方法要容易得多,即使用 R 变量来编写 LaTeX。

\documentclass{article}
<<include=FALSE>>=
French <- 1
@

<<results='asis'>>=
if (French == 1) cat('\\usepackage[French]{mytheme}')
@

\begin{document}

...

\end{document}

相关内容