# Knitr: storing variables for later use

I'm relatively new to Knitr. I want to run a function just once, so that next time I don't have to evaluate it, because it would yield a different result. My MWE:

First time:

\documentclass{article}

\begin{document}

<<>>=
a<<-Sys.time()
@

<<>>=
a
@

\end{document}


Second time:

\documentclass{article}

\begin{document}

<<eval=FALSE>>=
a<-Sys.time()
@

<<>>=
a
@

\end{document}


I've tried using <<- so that the variable is stored in the global environment but it doesn't work.

The document shows a repeated sample() function that overwrite the "a" object with random integers, but the last four are in a conditional function that only execute sample() if a does not exist, and this is only true in the first conditional because "a" was previously deleted:

\documentclass{article}
\begin{document}
<<echo=F>>=
# "a" change every time
a<- sample(1:1000, 1); a
a<- sample(1:1000, 1); a
a<- sample(1:1000, 1); a
a<- sample(1:1000, 1); a
rm(a)
# "a" change only the first time
if (exists("a")){a} else {a<- sample(1:1000, 1);a}
if (exists("a")){a} else {a<- sample(1:1000, 1);a}
if (exists("a")){a} else {a<- sample(1:1000, 1);a}
if (exists("a")){a} else {a<- sample(1:1000, 1);a}
@
\end{document}


The output should show five random numbers, where the last is repeated (not changed) three times, for example:

## [1] 220
## [1] 125
## [1] 113
## [1] 463
## [1] 701
## [1] 701
## [1] 701
## [1] 701