【问题标题】:Using a plot call in a function without evaluating it在函数中使用绘图调用而不评估它
【发布时间】:2020-08-29 09:41:46
【问题描述】:

在 Rmarkdown 文档中,我想通过仅在绘图尚未构建和保存时构建绘图来加速编织过程。

我使用下面的代码进行了此操作,并带有一个简单的示例。

x = rnorm(10)
if (! "figurename" %in% dir("figure")) {
    png("figure/figurename.png")
    hist(x)
    dev.off()
} 

现在我想创建一个函数,自动执行上述命令,并以绘图调用作为输入。此外,不应该评估情节调用(太慢了!)。我了解了substitute 命令并写了这个:

x = rnorm(10)
plot_call = substitute(hist(x))
function(plot_call, figurename){
    if (! figurename %in% dir("figure")) {
        png(file.path("figure", figurename))
        eval(plot_call)
        dev.off()
    } 
    knitr::include_graphics(file.path("figure", figurename))
}

我有两个问题:

  • 它似乎不适用于多线绘图调用
  • 这似乎是一个可疑的黑客攻击

你怎么看?有没有更好的办法?

【问题讨论】:

    标签: r function plot r-markdown


    【解决方案1】:

    缓存代码块的更正式的方法是利用chunk options。在块头添加一个简单的cache = TRUE 将强制您的绘图在每次块选项时重新评估,否则代码本身将会改变:

    ```{r expensive_plot, cache = TRUE}
    # Some expensive plot
    df %>%
        ggplot(aes(x, y)) +
        geom_point()
    ```
    

    如果每次基础数据发生更改时都需要重新计算绘图,则可以通过将cache.extra = file.mtime('your-csv.csv') 添加到您的选项中,在每次文件“上次编辑”字段更改时使缓存无效。

    【讨论】:

    • 谢谢,这正是我所需要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    相关资源
    最近更新 更多