更新:布兰登·贝特尔森的回答:
布兰登的答案产生以下输出。
它不会像 Rstudio 那样生成漂亮的表格或突出显示代码,并且它会在某些带有 unicode 的 html 文件上崩溃,因此我没有使用它来自动化我的电子邮件报告。
我目前的做法是用Rstudio编译为html,在chrome中打开html文档,然后将html文档复制粘贴到gmail中。这工作得很好,请看这个要点:https://gist.github.com/nelsonauner/a68b5a808c232ce7817e https://gist.github.com/nelsonauner/a68b5a808c232ce7817e
原问题:
有没有一种简单的方法可以将 R markdown 文档作为电子邮件正文发送,以便电子邮件正文看起来类似于使用 Rstudio 的“Knit HTML”的结果?
这是一个基本的可重现示例,使用knitr
, rmarkdown
, and mailR
示例.Rmd
---
title: "Report for email"
output:
html_document:
self_contained: no
---
```{r}
summary(cars)
```
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
```
我在用着self_contained: no
因为默认的 base64 编码不适用于mailR
(一辉推荐这个帖子 https://stackoverflow.com/questions/32520928/in-r-is-there-any-way-to-send-an-rmarkdown-v2-html-file-as-the-body-of-an-email)
knit_and_send.R
# compile using rmarkdown
library(rmarkdown)
rmarkdown::render("example.Rmd")
library(mailR)
send.mail(from = "[email protected] /cdn-cgi/l/email-protection",
to = "[email protected] /cdn-cgi/l/email-protection",
subject = "R Markdown Report - rmarkdown",
html = T,
inline = T,
body = "example.html",
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "me", passwd = "password", ssl = T),
authenticate = T,
send = T)
#compile using knitr
library(knitr)
knit2html("example.Rmd",options="")
send.mail(from = "[email protected] /cdn-cgi/l/email-protection",
to = "[email protected] /cdn-cgi/l/email-protection",
subject = "R Markdown Report - knitr",
html = T,
inline = T,
body = "example.html",
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "me", passwd = "password", ssl = T),
authenticate = T,
send = T)
两封邮件都发送成功。
针织电子邮件如下所示:
rmarkdown 电子邮件如下所示。 (请注意,它还包含一堆 JavaScript 文件——我想我必须编写一些脚本来删除它们)
但它们看起来都不如 Rstudio 的“Knit as HTML”生成的报告那么好,如下所示:
有什么建议么?
我认为真正的修复可能涉及对 html 文件进行一些后处理,以电子邮件友好的方式合并 css 样式,同时删除 javascript 文件。
现在,我将使用knitr
包裹。
如果有不清楚的地方,请告诉我,我会改进问题。
相关SO帖子:
在 R 中,有没有办法将 RMarkdown v2 html 文件作为电子邮件正文发送 https://stackoverflow.com/questions/32520928/in-r-is-there-any-way-to-send-an-rmarkdown-v2-html-file-as-the-body-of-an-email
mailR:如何将rmarkdown文档作为电子邮件正文发送? https://stackoverflow.com/questions/24346856/mailr-how-to-send-rmarkdown-documents-as-body-in-email