gpt4 book ai didi

r - 如何从 Rnw Sweave 文件中提取所有代码块?

转载 作者:行者123 更新时间:2023-12-01 20:25:14 34 4
gpt4 key购买 nike

我收到一个 .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)

}

最佳答案

这两种策略是Stangle(针对Sweave变体)和针对knitr变体的purl。我对 .Rnw 文件的印象是它们或多或少是等效的,但是 purl 也应该适用于其他类型的文件。

一些简单的例子:

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

无论哪种方式,您都可以使用source运行创建的代码文件。

注:This post描述了knitr的一个 block 选项,用于选择性地purl block ,这也可能有帮助。

关于r - 如何从 Rnw Sweave 文件中提取所有代码块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20288145/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com