Can I use a knitr inline expression in the title of a latex document?

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

I'd like to use a Knitr/Sweave in-line call (\Sexpr{}) in the title of a LaTeX document, after the \begin{document} command but before the \maketitle command. The in-line R code would extract one or two pieces of information from an R data-frame created early in the R script I'm embedding in LaTeX.

I have a couple of Knitr chunks that create a data.frame from which I derive the information I want to put in the Title. I've tried placing these chunks between LaTeX's \begin{document} call and the \title code, like this:

\documentclass [LaTex Preamble] \begin{document} [%% Knitr chunks that initialize an R data-frame] \title \Sexpr{--a snippet of R code that extracts an element from the data-frame --} \maketitle ... (rest of the LaTeX document) 

and I've also tried putting the Knitr chunks in the preamble to the LaTeX code before \begin{document} statement.

But in Knitr seems to ignore code (other than initialization) that is placed ahead of the \maketitle call in LaTeX, so the in-line snippets included the title look like errors to Latex and it halts output.

I can't find any information in the Knitr documentation on including in-line code in the Title of a LaTeX document.

Any ideas?


OK: Found the solution thanks to the hint from @ben-bolker below. Ben uses the formatting of R chunks before output to an RNW file (in a 2-step Knitr process: latex -> rnw -> pdf) . But I'm compiling the LaTeX file to PDF in one-step without going to an RNW file from inside TeXShop (on Mac OSX). I found that I could get Ben's example to work using the RNW delimiters (<<>>=) and one-step compiling. But I couldn't mix the usual LaTeX chunk-delimiters (%%begin.rcode and %% end.rcode) and the RNW in-line statement hook (\Sexpr{}). The latter didn't work no matter how I fiddled with it. Eventually I found that the correct in-line hook for LaTeX is \\rinline{}.

It's not very clear in the Knitr documentation that this is the required format for LaTeX and I found it eventually mainly thanks to Ben's example. Best, Peter


Update 2 ... and then there's RTFM (or the 'cheat sheet' in this case): http://cran.r-project.org/web/packages/knitr/vignettes/knitr-refcard.pdf

回答1:

Hmm. The following file works for me:

\documentclass{article} <<echo=FALSE>>= x <- 5 @  \title{The number is \Sexpr{x^2}} \begin{document} \maketitle  Some stuff \end{document} 

with knitr version 0.8 on Ubuntu 10.04, via knit2pdf("knitr_title.Rnw") ...



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!