渲染rmarkdown时Rscript和Rs源输出之间的差异

Ian*_*Ian 3 r knitr

我有一个构建脚本,将多个.Rmd文件编织成.md文件,我从以下调用方法得到不同的结果:

R -e source('bin/build_script.R')
Run Code Online (Sandbox Code Playgroud)

按预期工作,但是

Rscript bin/build_script.R
Run Code Online (Sandbox Code Playgroud)

没有按预期工作.生成的.md文件之间的区别与具有该行的代码块有关as(x, "Spatial").在第一种方法中,x转换,每个人都很高兴.使用Rscript调用会导致代码块返回错误

Error in as(x, "Spatial"): no method or default for coercing "sfc_POINT" to "Spatial"
Run Code Online (Sandbox Code Playgroud)

Rscript和源处理导入库的方式有所不同吗?

这是我的构建脚本:

require(knitr)
require(yaml)
require(stringr)

config = yaml.load_file('docs/_config.yml')
render_markdown(fence_char = '~')
opts_knit$set(
    root.dir = '.',
    base.dir = 'docs/',
    base.url = '{{ site.baseurl }}/')
opts_chunk$set(
    comment = NA,
    fig.path = 'images/',
    block_ial = c('{:.input}', '{:.output}'),
    cache = FALSE,
    cache.path = 'docs/_slides_Rmd/cache/')

current_chunk = knit_hooks$get('chunk')
chunk = function(x, options) {
    x <- current_chunk(x, options)
    if (!is.null(options$title)) {
        # add title to kramdown block IAL
        x <- gsub('~~~(\n*(!\\[.+)?$)',
                  paste0('~~~\n{:.text-document title="', options$title, '"}\\1'),
                  x)
        # move figures to <div> on next slide
        x <- gsub('(!\\[.+$)', '===\n\n\\1\n{:.captioned}', x)
    } else {
        # add default kramdown block IAL to kramdown block IAL to input
        x <- gsub('~~~\n(\n+~~~)',
                  paste0('~~~\n', options$block_ial[1], '\\1'),
                  x)
        if (str_count(x, '~~~') > 2) {
            idx <- 2
        } else {
            idx <- 1
        }
        x <- gsub('~~~(\n*$)',
                  paste0('~~~\n', options$block_ial[idx], '\\1'),
                  x)
    }
    return(x)
}
knit_hooks$set(chunk = chunk)

files <- list.files('docs/_slides_Rmd')
for (f in config$slide_sorter) {
    f.Rmd <- paste0(f, '.Rmd')
    if (f.Rmd %in% files) {
        f.md <- paste0(f, '.md')
        knit(input = file.path('docs/_slides_Rmd', f.Rmd),
             output = file.path('docs/_slides', f.md))
    }
}
Run Code Online (Sandbox Code Playgroud)

Dir*_*tel 7

这是一个古老的"功能"和值得FAQ中的: Rscript在其永恒的智慧并没有加载methods附带基础R,并且需要正确与S4类应付包.

只需library(methods)在脚本中添加一行即可.

或者使用利特勒,而不是Rscript它不会加载它:)