Making knitr run a r script: do I use read_chunk or source?

read_chunk() only reads the source code (for future references); it does not evaluate code like source(). The purpose of read_chunk() was explained in this page as well as the manual.


In case it helps anyone else, I've found using read_chunk() to read a script without evaluating can be useful in two ways. First, you might have a script with many chunks and want control over which ones run where (e.g., a plot or a table in a specific place). I use source when I want to run everything in a script (for example, at the start of a document to load a standard set of packages or custom functions). I've started using read_chunk early in the document to load scripts and then selectively run the chunks I want where I need them.

Second, if you are working with an R script directly or interactively, you might want a long preamble of code that loads packages, data, etc. Such a preamble, however, could be unnecessary and slow if, for example, prior code chunks in the main document already loaded data.


There isn't an option to run a chunk interactively from within knitr AFAIK. However, this can be done easily enough with something like:

#' Run a previously loaded chunk interactively
#'
#' Takes labeled code loaded with load_chunk and runs it in the /global/ envir (unless otherwise specified)
#'
#' @param chunkName The name of the chunk as a character string
#' @param envir The environment in which the chunk is to be evaluated 
run_chunk <- function(chunkName,envir=.GlobalEnv) {
    chunkName <- unlist(lapply(as.list(substitute(.(chunkName)))[-1], as.character))    
    eval(parse(text=knitr:::knit_code$get(chunkName)),envir=envir) 
} 
NULL

Tags:

R

Rstudio

Knitr