如何从Rnw Sweave文件中提取所有代码块? [英] How to extract all code chunks from a Rnw Sweave file?

查看:86
本文介绍了如何从Rnw Sweave文件中提取所有代码块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个.Rnw文件,该文件在尝试构建其所属的软件包时出现错误.问题是,当使用RStudio中的工具检查软件包时,没有任何有用的错误信息.因此,我需要首先找出发生错误的代码行.

I received a .Rnw file that gives errors when trying to build the package it belongs to. Problem is, when checking the package using the tools in RStudio, I get no useful error information whatsoever. So I need to figure out first on what code line the error occurs.

为了弄清楚这一点,我编写了这个5分钟的黑客程序,以将所有代码块保存在一个单独的文件中.我有一种感觉,虽然我想念一些东西.就像运行脚本文件一样,提取Rnw文件中所有代码的干净方法是什么?是否有一个功能可以全部提取或以一种可以找出错误发生在哪一行的方式运行所有函数?

In order to figure this out, I wrote this 5-minute hack to get all code chunks in a separate file. I have the feeling though I'm missing something. What is the clean way of extracting all code in an Rnw file just like you run a script file? Is there a function to either extract all, or run all in such a way you can find out at which line the error occurs?

我的骇客:

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用于编织器变体.我对.Rnw文件的印象是它们或多或少等效,但是purl也应该适用于其他类型的文件.

The two strategies are Stangle (for a Sweave variant) and purl for a knitr variant. My impression for .Rnw files is that they are more or less equivalent, but purl should work for other types of files, as well.

一些简单的例子:

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

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

Either way you can then run the created code file using source.

注意:这篇文章描述了knitr有选择地选择purl的一个大块选项.块,这可能也有帮助.

Note: This post describes an chunk option for knitr to selectively purl chunks, which may be helpful, too.

这篇关于如何从Rnw Sweave文件中提取所有代码块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆