根据 tibble 中的数据发送电子邮件

Send emails based on data in tibble

我正在尝试迭代 tibble 以从每一行发送电子邮件,但无法正常工作。这是示例:

library(tidyverse)
library(sendmailR)
library(pander)

首先创建table我想包含到电子邮件

tbl <- tibble(A = c(1,2,3),
              B = c(4,5,6),
              C = c(7,8,9))

table <- pander_return(tbl)

创建tibble,每列对应我要包含在电子邮件中的某些信息

emails <- tibble(from = c("jane.doe@gm.com", "john.doe@gm.com"),
                 to = c("jane.doe@gm.com", "john.doe@gm.com"),
                 subject = "This is test",
                 greetings = "Happy Christmas",
                 data = list(table, table))

现在我想 map 每一列并将其添加到 sendmailR 包中 sendmail 函数的正确位置。这是我如何发送一封电子邮件的示例。唯一有趣的一点是如何将 greetingstable 连接在一起以创建 msg 字段。

from <- "jane.doe@gm.com"
to <- "jane.doe@gm.com"
subject <- "This is test"
msg <- c(greetings, table)

sendmailR::sendmail(from = from, to = to, subject = subject, msg = msg)

那么我如何才能将电子邮件 tibble 映射到 sendmail 函数,以便每一行发送电子邮件。

这是 purrr

pmap 函数的完美用例

您可以执行以下操作

pmap( list(emails$from, emails$to, emails$subject, emails$data) 
      , ~sendmailR::sendmail(from = ..1, 
                            to = ..2, 
                            subject = ..3, 
                            msg = ..4))

这将创建一个参数列表,然后使用 ~ 我们定义函数。 ..x 表示参数在输入列表中出现的顺序。

完全代表

library(tidyverse)
library(sendmailR)
library(pander)

tbl <- tibble(A = c(1,2,3),
              B = c(4,5,6),
              C = c(7,8,9))

table <- pander_return(tbl)

emails <- tibble(from = c("jane.doe@gm.com", "john.doe@gm.com"),
                 to = c("jane.doe@gm.com", "john.doe@gm.com"),
                 subject = "This is test",
                 greetings = "Happy Christmas",
                 data = list(greetings, table))

pmap( list(emails$from, emails$to, emails$subject, emails$data) 
      , ~sendmailR::sendmail(from = ..1, 
                            to = ..2, 
                            subject = ..3, 
                            msg = ..4))

并且只是为了证明它适用于较低赌注的功能:

pmap( list(emails$from, emails$to, emails$subject, emails$data) 
      , ~paste(..1, 
                            ..2, 
                            ..3))

输出:

[[1]]
[1] "jane.doe@gm.com jane.doe@gm.com This is test"

[[2]]
[1] "john.doe@gm.com john.doe@gm.com This is test"