我收到了一个.Rnw文件,在尝试构建它所属的包时会出错.问题是,当使用RStudio中的工具检查包时,我没有得到任何有用的错误信息.所以我需要首先弄清楚错误发生在哪个代码行上.
为了弄清楚这一点,我写了这个5分钟的黑客攻击,将所有代码块放在一个单独的文件中.我有这种感觉,虽然我错过了一些东西.像运行脚本文件一样,提取Rnw文件中所有代码的简洁方法是什么?是否有一个函数要么全部提取,要么以这种方式运行所有可以找出错误发生在哪一行?
我的黑客:
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) }
解决方法
这两种策略是Stangle(用于Sweave变体)和purl用于knitr变体.我对.Rnw文件的印象是它们或多或少相同,但purl也适用于其他类型的文件.
一些简单的例子:
f <- 'somefile.Rnw' knitr::purl(f) Stangle(f)
无论哪种方式,您都可以使用source运行创建的代码文件.
注意:This post描述了knitr选择性地清除块的块选项,这也可能有用.