can knitr 'remember' a previously knitted result?

26 views
Skip to first unread message

Vincent Nijs

unread,
May 9, 2015, 2:42:02 AM5/9/15
to kn...@googlegroups.com
I have been using shinyAce as an editor in a shiny app where users can enter R-markdown or R-code and run it (as least when the app is installed locally). ShinyAce allows you to select chunks of code and you can use this to only evaluate the selected lines of code. I use knitr to evaluate the code and print the output. This works fine unless data/variables were defined in a previously evaluate chunk of code. To illustrate, if the lines below are selected together you get `3` as the result. However, if you run the first and second line separately you of course get `Error in print(x) : object 'x' not found`. 

x <- 3
print(x)

The code used in the app to knit the user input is here: https://github.com/vnijs/radiant/blob/master/inst/base/tools/app/report.R#L309-L311

So here is the is the question: Is there an option for knitr to 'remember' values from previously executed lines of code. I am not looking for cache = TRUE. That would work if you are rerunning the *same* lines of code. I looking for something similar to executing lines of code one-by-one in, for example, R-studio.

You can see the app here: https://vnijs.shinyapps.io/marketing/  (go to R > Code). Unfortunately you cannot evaluate code on the server so if you want to see this working you will have to install locally with the command below. 

install.packages("radiant", repos = "http://vnijs.github.io/radiant_miniCRAN/")

Stéphane Laurent

unread,
May 19, 2015, 7:56:09 AM5/19/15
to kn...@googlegroups.com
Hello,

I think you can use an environment in the envir option of knit2html : 

> myenv <- new.env()
> ls(myenv)
character
(0)
> test <- knit2html(text="`r x <- 2`", envir=myenv)
 
|.................................................................| 100%
   
inline R code fragments




> ls(myenv)
[1] "x"

Vincent Nijs

unread,
May 19, 2015, 1:36:47 PM5/19/15
to kn...@googlegroups.com
Excellent! That is exactly what I was looking for Stéphane
Reply all
Reply to author
Forward
0 new messages