How to extract all code chunks from a Rnw Sweave file?

extract, file, r, sweave, text

Solution

The two strategies are `Stangle` (for a Sweave variant) and `purl` for a knitr variant. My impression for .Rnw files is that they are more or less equivalent, but `purl` should work for other types of files, as well.

Some simple examples:

f <- 'somefile.Rnw'
knitr::purl(f)
Stangle(f)

Either way you can then run the created code file using `source`.

Note: This post describes an chunk option for knitr to selectively `purl` chunks, which may be helpful, too.

Problem

I received a .Rnw file that gives errors when trying to build the package it belongs to. Problem is, when checking the package using the tools in RStudio, I get no useful error information whatsoever. So I need to figure out first on what code line the error occurs. In order to figure this out, I wrote this 5-minute hack to get all code chunks in a separate file. I have the feeling though I'm missing something. What is the clean way of extracting all code in an Rnw file just like you run a script file? Is there a function to either extract all, or run all in such a way you can find out at which line the error occurs? My hack: ``` ExtractChunks <- function(file.in,file.out,...){ isRnw <- grepl(".Rnw$",file.in) if(!isRnw) stop("file.in should be an Rnw file") thelines <- readLines(file.in) startid <- grep("^[^%].+>>=$",thelines) nocode <- grep("^<<",thelines[startid+1]) # when using labels. codestart <- startid[-nocode] out <- sapply(codestart,function(i){ tmp <- thelines[-seq_len(i)] endid <- grep("^@",tmp)[1] # take into account trailing spaces / comments c("# Chunk",tmp[seq_len(endid-1)]) }) writeLines(unlist(out),file.out) } ```

Original source