使用knitr 將類別/包/主題選項傳遞給 R

使用knitr 將類別/包/主題選項傳遞給 R

我有一個beamer包含區塊的文檔R,例如“template.Rnw”,我knitr使用“compile PDF”進行編譯RStudio。我定義了一個主題「mytheme.sty」。我希望有一個名為“主題”的選項French,並在文件頂部這樣稱呼它:

    \usetheme[French]{mytheme}

這個「法國」主題定義了與美國風格不同的圖形標籤格式選項,例如$1,000,000.00列印為1 000 000,00$.

我想我可以French == 1在“mytheme.sty”中建立一個布林值,然後將其傳遞給一個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}

神話主題.sty

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

陰謀 與課外獲得Rbeamer

在此輸入影像描述

答案1

沒有辦法(至少不是直接的辦法)將LaTeX變數傳遞給R。

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

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

\begin{document}

...

\end{document}

相關內容