Search code examples
rr-box

using klmr box::use in an rmarkdown document


Can anyone give me an example to add libraries and local functions with the klmr::box package in a rmarkdown document?

I am aware of their use in Rhino´s framework, but I feel a bit confused where can I declare modules and libraries in a YAML + Rmarkdown file.


Solution

  • The way is to remember he location of the .Rmd file. The difference with the package here::here is that it does not go backwards from the .Rmd location. box yes, using .. in fromt of module's statements.

    ```{r setup, include=FALSE, warning=FALSE, echo=FALSE}
    box::use(
      r/core[...],
      dplyr[
        `%>%`, mutate, across, rename, case_when, if_else,
        select, filter, group_by, left_join, summarise, pull, arrange, desc,
        n, n_distinct
      ],
      tidyr[pivot_wider, fill, complete, nesting, replace_na],
      glue[glue],
    )
    
    box::use(../data/constants)
    box::use(../logic/some_function_in_project)
    box::use(../logic/dependencies)
    
    # example of alias
    kable_formating <- dependencies$kable_formating$kable_formating
    ```
    

    In their invocation, keep one eye in the relative locations:

    • input, output: not passed to the internal .Rmd. So they begin from the current working enviroment where render is executed.

    • lib, math, css: are relative to the final output file location.

    • the knit_root_dir param can change the working directory where render and knit is executed. Keep it in mind this possibility if your .Rmd calls from inside modules to readjust their locations.

      rmarkdown::render(
        input = 'doc/document.Rmd',
        output_format = 'prettydoc::html_pretty',
        output_file = output_filename,
        output_dir = output_dir,
        output_options = list(
          self_contained = TRUE,
          math = NULL,
          # lib_dir must be relative to the .Rmd
          # el .Rmd is in doc/
          # so go back to the doc's root with ".."
          # and go up with /reports/site_libs
          lib_dir = "../reports/site_libs",
          # css is relative to the output directory
          # aquí conviene duplicar la css en la carpeta output
          # for some reason, file.path does not work with css parameter
          css = paste("www", "style.css", sep = "/")
        ),
        params = list(
          id_prospect = id_prospect,
          dsn = dsn,
          pwd = pwd
        )
      )