Search code examples
rlatexsweave

Is it possible to include a Sexpr before the expression has been evaluated in Sweave / R?


I'm writing a Sweave document, and I want to include a small section that details the R and package versions, platofrms and how long ti took to evalute the doucment, however, I want to put this in the middle of the document !

I was using a \Sexpr{elapsed} to do this (which didn't work), but thought if I put the code printing elapsed in a chunk that evaluates at the end, I could then include the chunk half way through, which also fails.

My document looks something like this

% 
\documentclass[a4paper]{article}
\usepackage[OT1]{fontenc}
\usepackage{longtable}
\usepackage{geometry}
\usepackage{Sweave}
\geometry{left=1.25in, right=1.25in, top=1in, bottom=1in}
\begin{document}

<<label=start, echo=FALSE, include=FALSE>>=
startt<-proc.time()[3]
@ 
Text and Sweave Code in here
% 
This document was created on \today, with \Sexpr{print(version$version.string)} running
 on a \Sexpr{print(version$platform)} platform. It took approx sec to process.
<<>>=
    <<elapsed>>
@ 
More text and Sweave code in here
<<label=bye, include=FALSE, echo=FALSE>>= 
odbcCloseAll()
endt<-proc.time()[3]
elapsedtime<-as.numeric(endt-startt)
@ 
<<label=elapsed, include=FALSE, echo=FALSE>>=
print(elapsedtime)
@ 
\end{document}

But this doesn't seem to work (amazingly !)

Does anyone know how I could do this ?

Thanks

Paul.


Solution

  • This works just fine for me:

    \documentclass{article}
    \usepackage{Sweave}
    \begin{document}
    
    <<label=start, echo=FALSE, include=FALSE>>=
    startt<-proc.time()[3]
    @
    
    Text and Sweave Code in here
    
    This document was created on \today, with
    \Sexpr{print(version$version.string)}.
    
    <<results=hide,echo=FALSE>>=
    Sys.sleep(2)  # instead of real work
    @
    
    More text and Sweave code in here
    
    <<label=bye, include=FALSE, echo=FALSE>>=
    endt<-proc.time()[3]
    elapsedtime<-as.numeric(endt-startt)
    @
    
    It took approx \Sexpr{elapsedtime} seconds to process.
    
    \end{document}
    

    I had to remove the version string inside the \Sexp{} as I get an underscore with via x86_64 which then upsets LaTeX. Otherwise just fine, and you now get the elapsed time of just over the slept amount.

    You could use either R to cache the elapsed time in a temporary file for the next run, or pass it to LaTeX as some sort of variable -- but you will not be able to use 'forward references' as the R chunks gets evaluated in turn.