【问题标题】:With knitr, preserve chunk options when purling chunks into separate files使用 knitr,在将块合并到单独的文件时保留块选项
【发布时间】:2016-06-21 17:12:57
【问题描述】:

出于教学目的,我想将purl 我的.Rnw 文件的块分成单独的文件。这个答案解释了如何做到这一点:

How to purl each chunks in .Rmd file to multiple .R files using Knitr

但是该方法不保留块选项。由于我已经生成了块,因此保留 fig.widthfig.height 选项很重要。理想情况下,我想要一个如下所示的块:

<<plot, fig.width = 3, fig.height = 5, outwidth = '.75\\textwidth'>>=
plot (1,1)
@

变成一个名为plot.R 的文件,如下所示:

#+ fig.width = 3, fig.height = 5
plot (1,1)

也就是说,将块选项fig.widthfig.height转换为spin()可以识别的格式,就像purl()所做的那样,去掉不相关的块选项,或者为spin() 转入 Word,如 out.width。一切都本着创建用户友好的代码文件的精神。

【问题讨论】:

    标签: r knitr rnw


    【解决方案1】:

    由于您引用的答案没有从purl 的结果中复制标题行,因此您会丢失除块名称之外的所有内容。虽然您可以调整它以粘贴到标题中,但实际上构建一个函数来解析 purl 的输出并不难——这比尝试解析 RmdRnw 文档容易得多,而且比排序更容易弄清楚knitr 是如何做到的。

    purl_chunks <- function(input_file){
      purled <- knitr::purl(input_file)    # purl original file; save name to variable
      lines <- readLines(purled)    # read purled file into a character vector of lines
      starts <- grep('^## ----.*-+', lines)    # use grep to find header row indices
      stops <- c(starts[-1] - 1L, length(lines))   # end row indices
      # extract chunk names from headers
      names <- sub('^## ----([^-]([^,=]*[^,=-])*)[,-][^=].*', '\\1', lines[starts])
      names <- ifelse(names == lines[starts], '', paste0('_', names)) # clean if no chunk name
      # make nice file names with chunk number and name (if exists)
      file_names <- paste0('chunk_', seq_along(starts), names, '.R')
      for(chunk in seq_along(starts)){    # loop over header rows
        # save the lines in the chunk to a file
        writeLines(lines[starts[chunk]:stops[chunk]], con = file_names[chunk])
      }
      unlink(purled)    # delete purled file of entire document
    }
    

    几个注意事项:

    • 虽然正则表达式适用于我提出的问题,但它可能仍然存在错误。测试:
      • 没有区块名称
      • 没有名称,只有块设置
      • 带有连字符的名称
      • 单个字符名称
      • 带有空格的名称,包括之后(逗号/大括号之前)
    • 由于.Rnw.Rmd 文件都purl 相同,它适用于任何一个。
    • 它使用purldocumentation 参数的默认设置(1L)。 0L 不会有块头,因此无论如何在这里毫无意义,但它会愚蠢地处理2L(它将包括文本块作为roxygen cmets)。但是,如果您想要具有以下代码块的文本块,则可以为此重建它。
    • 虽然purl 的输出标题行看起来与您上面的示例不完全相同(它们以## ---- 开头并用连字符填充),但它们spin 正确;结果服从块选项。

    【讨论】:

    • 太棒了,就像一个魅力。太感谢了。这就是我希望我知道该怎么做...我会研究它并学习。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 2021-07-11
    相关资源
    最近更新 更多