【问题标题】:How to extract all code chunks from a Rnw Sweave file?如何从 Rnw Sweave 文件中提取所有代码块?
【发布时间】: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


【解决方案1】:

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

一些简单的例子:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多