1

I find myself using rmarkdown/rnotebooks quite a bit to do exploratory analysis since I can combine code, prose and graphs. Many a times, I'll write my entire predictive modeling approach and the model itself within markdown.

However, then I end up with forecast models embedded within rmarkdown, unlinked to a target within my drake_plan. Today, I save these to disk first, then read them back in to my plan using file_in or other similar approach.

My question is - can I have a markdown document return an object directly to a drake target?

Conceptually:

plan = drake_plan(
    dat = read_data(),
    model = analyze_data(dat)
)

analyse_data = function(dat){
    result = render(....)
    return(result)
}

This way - I can get my model directly into my drake target, but if I need to investigate the model, I can open up my markdown/HTML.

Rahul
  • 2,579
  • 1
  • 13
  • 22

1 Answers1

1

I recommend you include those models as targets in the plan, but what you describe is possible. R Markdown and knitr automatically run code chunks in the calling environment, so the variable assignments you make in the report are available.

library(drake)
library(tibble)

simulate <- function(n){
  tibble(x = rnorm(n), y = rnorm(n))
}

render_and_return <- function(input, output) {
  rmarkdown::render(input, output_file = output, quiet = TRUE)
  return_value # Assigned in the report.
}

lines <- c(
  "---",
  "output: html_document",
  "---",
  "",
  "```{r show_data}",
  "return_value <- head(readd(large))", # return_value gets assigned here.
  "```"
)

writeLines(lines, "report.Rmd")

plan <- drake_plan(
  large = simulate(1000),
  subset = render_and_return(knitr_in("report.Rmd"), file_out("report.html")),
)

make(plan)
#> target large
#> target subset

readd(subset)
#> # A tibble: 6 x 2
#>        x       y
#>    <dbl>   <dbl>
#> 1  1.30  -0.912 
#> 2 -0.327  0.0622
#> 3  1.29   1.18  
#> 4 -1.52   1.06  
#> 5 -1.18   0.0295
#> 6 -0.985 -0.0475

Created on 2019-10-10 by the reprex package (v0.3.0)

landau
  • 5,636
  • 1
  • 22
  • 50