问题
In the cache directory, one can use lazyLoad
to view the environment at the end of a chunk. But where is the output of the chunk (that will be printed if the document is compiled) stored?
回答1:
Use the source!
Look at the source code here https://github.com/yihui/knitr/blob/master/R/cache.R
You can see that the mechanism is explained here (within the new_cache
function)
# when cache=3, code output is stored in .[hash], so cache=TRUE won't lose
# output as cacheSweave does; for cache=1,2, output is the evaluate() list
cache_output = function(hash, mode = 'character') {
get(sprintf('.%s', hash), envir = knit_global(), mode = mode, inherits = FALSE)
}
I.e. it is stored as an object in the knit_global
environemnt`
You can inspect these objects by ls(knitr::knit_global(), all = TRUE)
I.e. the 3 simple chunks below
```{r, cache=TRUE}
summary(cars)
```
```{r }
ls(knitr::knit_global(), all = TRUE)
```
```{r }
get(ls(knitr::knit_global(), all = TRUE)[1], knitr::knit_global())
```
Give following output
summary(cars)
## speed dist
## Min. : 4.0 Min. : 2
## 1st Qu.:12.0 1st Qu.: 26
## Median :15.0 Median : 36
## Mean :15.4 Mean : 43
## 3rd Qu.:19.0 3rd Qu.: 56
## Max. :25.0 Max. :120
ls(knitr::knit_global(), all = TRUE)
## [1] ".Preview-2b40490e2591_cache/unnamed-chunk-1_766fcb86fd875984b372e3c23210bfad"
## [2] "metadata"
get(ls(knitr::knit_global(), all = TRUE)[1], knitr::knit_global())
## [1] "\n```r\nsummary(cars)\n```\n\n```\n## speed dist \n## Min. : 4.0 Min. : 2 \n## 1st Qu.:12.0 1st Qu.: 26 \n## Median :15.0 Median : 36 \n## Mean :15.4 Mean : 43 \n## 3rd Qu.:19.0 3rd Qu.: 56 \n## Max. :25.0 Max. :120\n```"
If you have exited R, you can load the data from the file *.RData in the cache folder using the load
command. Also, to output the result of get
, consider to use cat
which will turn the "\n" into lines and should look like original output.
来源:https://stackoverflow.com/questions/23721859/where-is-knitr-cached-output-stored