Jor*_*eys 3 text r file extract sweave
我收到了一个.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)
}
Run Code Online (Sandbox Code Playgroud)
Tho*_*mas 12
这两个策略是Stangle(对于Sweave变体)和purl一个knitr变种.我对.Rnw文件的印象是它们或多或少相同,但purl也适用于其他类型的文件.
一些简单的例子:
f <- 'somefile.Rnw'
knitr::purl(f)
Stangle(f)
Run Code Online (Sandbox Code Playgroud)
无论哪种方式,您都可以使用运行创建的代码文件source.
注意:这篇文章描述了针对选择性purl块的knitr的块选项,这也可能有用.