【发布时间】:2013-11-29 14:39:22
【问题描述】:
我收到一个 .Rnw 文件,它在尝试构建它所属的包时出错。问题是,在使用 RStudio 中的工具检查包时,我没有得到任何有用的错误信息。所以我需要先弄清楚错误发生在哪个代码行。
为了弄清楚这一点,我编写了这个 5 分钟的 hack,将所有代码块放在一个单独的文件中。我有一种感觉,虽然我错过了一些东西。像运行脚本文件一样提取 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)
}
【问题讨论】:
-
使用 sweave 打结或使用 knitr 打结。
-
@Thomas 如果你把它放在答案中,我可以给你功劳。
标签: r file text extract sweave