簡體   English   中英

如何使我的函數(幾個ggplot2圖形)的輸出成為html文件(顯示這些圖形)?

[英]How can I make the output of my function (several ggplot2 graphs) an html file (displaying those graphs)?

我正在編寫一個用於訓練/測試模型的個人使用包,最后在它們上運行了許多LIMEDALEX解釋。 我將它們另存為自己的ggplot2對象(例如lime_plot_1 ),並在函數結束時將它們全部返回到全局環境。

但是,我想發生的事情是,在函數的結尾,我不僅將這些圖形放在環境中,而且還將呈現一個小的html報告-包含所有已創建的圖形。

我想指出的是,雖然我確實知道可以通過簡單地使用Rmarkdown或Rnotebook中的函數來做到這一點,但我希望避免這種情況,因為我計划將其用作.R腳本以簡化整個過程(因為我將以一定的頻率運行它,根據我的經驗,在.Rmd中運行大塊代碼會導致R崩潰。

理想情況下,我會有這樣的東西:

s_plot <- function(...){

 1. constructs LIME explanations
 2. constructs DALEX explanations
 3. saves explanations as ggplot2 objects, and list them under graphs_list

 4. render graphs_list as an html file
}

1、2和3都可以工作,但是我還沒有找到解決4.的方法,這不包括在.Rmd文件中進行整個過程。

編輯:感謝@Richard Telford和@Axeman的評論,我弄清楚了。 下面是功能:

s_render <- function(graphs_list = graphs_list, meta = NULL, cacheable = NA){

    currentDate <- Sys.Date()

    rmd_file <- paste("/path/to/folder",currentDate,"/report.Rmd", sep="")

    file.create(rmd_file)

    graphs_list <- c(roc_plot, prc_plot, mp_boxplot, vi_plot, corr_plot)

    c(Yaml file headers here, just like in a regular .Rmd) %>% write_lines(rmd_file)
    rmarkdown::render(rmd_file,
            params = list(
                    output_file = html_document(),
                    output_dir = rmd_file))}

首先,創建一個簡單的Rmarkdown文件,該文件帶有一個參數。 該文件的唯一目的是創建報告。 例如,您可以傳遞文件名:

---
title: "test"
author: "Axeman"
date: "24/06/2019"
output: html_document
params:
  file: 'test.RDS'
---

```{r}
plot_list <- readRDS(params$file)
lapply(plot_list, print)
```

我將其保存為test.Rmd

然后在您的主腳本中,將繪圖列表寫入磁盤上的臨時文件,並將文件名傳遞給降價報告:

library(ggplot2)
plot_list <- list(
  qplot(1:10, 1:10),
  qplot(1:10)
)

file <- tempfile()
saveRDS(plot_list, file)
rmarkdown::render('test.Rmd', params = list(file = file))

包含繪圖的.html文件現在位於磁盤上:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM