using the params arg in emayili::render()

Viewed 82

I'm trying to write a code that automates emailing (with emayili) R markdown reports with filtered data. Each user (email) should get his\her own unique filtered data fed into the email report.

My solution was to define a filter based on an R markdown parameter, and then (for) loop over the params arg in the render() function, outside the .Rmd file in a separate .R script. That way each user would get a unique markdown report with his\her filtered data. However that was not possible, since the params arg is not specified in the emayili::render wrapper function.

Is there a workaround? Perhaps I could render outside emayili::envelope(), using rmarkdown::render(), and then feed the outputted html(s) files into the emayili::html() function? I couldn't make that work either.

Thanks, Yoav

1 Answers

I'm not too familiar with the emayili package, and I'm somewhat surprised that it doesn't offer parameter setting, since that would be a prime use case. The doc do seem to suggest that it currently isn't featured, so you might want to raise a feature request with the author. (Update: as per the comment below, this feature has been added, see here for details)

In the meantime, there are a couple of options:

Use the environment to set variables

You can design the .rmd file such that it picks up global variables from your emayili code:

username = 'Jabberwocky'
msg <- envelope() %>% render('template.Rmd') #.rmd picks up username and filters accordingly

Use this solution with caution, relying on global variables tends to be a headache.

Manually manipulate .rmd file using string replacements

Create an rmd file of the form

---
title: 'Email title'
#... your other stuff...
params:
   username: $USERNAME$
---

and in the program perform a replacement action:

rmdtext = read_rmd_from_file(filename) # Using your favourite method of text loading
rmdtext = gsub('$USERNAME', 'Jabberwocky', rmdtext)
msg <- envelope() %>% render(rmdstring)

Use rmdmanip

Shameless self-plug of a package I created: you can use rmdmanip to manipulate rmd parameters.

devtools::install_github('minimumcosttohumanity/rmdmanip')

The package directly manipulates parameters in an rmd string or file:

library(rmdmanip)
# Load file and replace parameters directly in text
rmdstring = read.rmd(filename) %>% 
      put_param('username', 'Jabberwocky') %>% 
      dumps()
msg <- envelope() %>% render(rmdstring)
Related