Skip to content

rmarkdown::render(output_dir=) should be taken into account of knitr::include_graphics() #2473

Open

Description

@multimeric

This is a problem because output.dir is the output directory as understood by knitr. Paths passed to include_graphics(), for example, are made relative to output.dir. When we set rmarkdown::render(output_dir=), a user might reasonably expect that this would change the output.dir, and their document may fail in confusing ways when handling relative paths. In fact there seems to be no mechanism for setting the output.dir externally, which can make it very difficult to knit the same document to two different places, because the relative paths will be wrong in one of the cases.

Example

We have an RMarkdown document:

knitr::opts_knit$get("output.dir")

We knit it using: rmarkdown::render("UntitledRMD.Rmd", output_dir="foo")

Inside the vignette, this prints a directory that is not foo.

> xfun::session_info('rmarkdown')
R version 4.2.1 (2022-06-23)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core), RStudio 2023.3.0.386.1

Locale:
  LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
  LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8    LC_PAPER=en_US.UTF-8       LC_NAME=C                 
  LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

Package version:
  base64enc_0.1.3 bslib_0.4.2     cachem_1.0.6    cli_3.6.0       digest_0.6.31   ellipsis_0.3.2  evaluate_0.19   fastmap_1.1.0  
  fs_1.5.2        glue_1.6.2      graphics_4.2.1  grDevices_4.2.1 highr_0.10      htmltools_0.5.4 jquerylib_0.1.4 jsonlite_1.8.4 
  knitr_1.41      lifecycle_1.0.3 magrittr_2.0.3  memoise_2.0.1   methods_4.2.1   mime_0.12       R6_2.5.1        rappdirs_0.3.3 
  rlang_1.0.6     rmarkdown_2.20  sass_0.4.4      stats_4.2.1     stringi_1.7.12  stringr_1.5.0   tinytex_0.43    tools_4.2.1    
  utils_4.2.1     vctrs_0.5.2     xfun_0.36       yaml_2.3.6     

Pandoc version: 2.19.2

Activity

  1. cderv commented on Apr 17, 2023

    @cderv
    Collaborator

    Thanks for your feedback. I would like to try clarify the current situation, and know more about the exact issue you are encountering. This will help better understand the solution you are suggesting regarding output.dir which internal to knitr

    First output.dir is a value internal to knitr. It is not documented among available options to tweak and it is used to store the current working directory of the knitting step
    https://github.com/yihui/knitr/blob/e8aae19fcc7443b8a212c8dc65ba2b83894f1fe0/R/output.R#L159-L160
    Currently the value is set to the current working dir of knitr::knit() call and it is used when the original working directory is needed, like child mode context, cache handling. It was added to include_graphics() last year in yihui/knitr@516b6f5 to fix yihui/knitr#2119 so that absolute paths are converted to relative path based on the original working directory.

    output_dir in rmarkdown has another meaning. It is not exactly the same purpose. It is used to compute where the resources and output for rmarkdown::render() are placed. Not the one for the knitted step, but the results after knit + pandoc conversion.
    I don't think they are or should be equivalent. Also because output_dir is user facing, and output.dir is internal.

    They are currently not meant to be equal as rmarkdown::render() sets the working dir to be the root directory of the input file so output.dir internally to knitr will be set to that. ouput_dir is used to compute some paths for outputs inside rmarkdown processing.

    For all this context, I would like to understand better the problem you are identifying by

    When we set rmarkdown::render(output_dir=), a user might reasonably expect that this would change the output.dir, and their document may fail in confusing ways when handling relative paths.

    output.dir usage being internal to knitr, changing could have a broad impact so we need to be sure of the underlying issue and why we would change it. Maybe the recent change in include_graphics() is not good enough and we should adapt that instead.

    To help us further, can you build an example that reproduce the issue you have with your graphics relative path ? This would be the best for us to look into and really see if the solution suggested match the usage problem identified.

    Thank you very much !

  2. multimeric commented on Apr 17, 2023

    @multimeric
    Author

    Thanks for the informative answer.

    Here's my concrete use case. I have one vignette, which lives in vignettes. I want to be able to render it two different ways. The first is as a vignette, to html, using the normal vignette mechanism. The second is to render it to github_markdown, to use as a readme. The issue is that the image paths are not the same in these two use cases. In the former case, I want img.png, in the latter case I want vignettes/img.png. Therefore, I want to be able to tell RMarkdown "this is where I want my document to think it is located", namely "this is the directory I want images to be relative to". output.dir seems to be exactly this, since it's the directory that knitr makes images relate to. It seems that this option should be treated as private (which is possibly why setting it via options() and via knitr::opts_knit$set outside of the document don't seem to work!), so how should I do this? Here is a repo where I demonstrate what I want to happen and how I have currently solved it: https://github.com/multimeric/KnitrPortable

    From what you've said, it sounds like I should be setting the working directory and output.dir will inherit from this. Can you show me an example of how I should be doing this?

    I totally understand the different meaning of rmarkdown's output_dir, and I think that's valuable as its own option independent from output.dir. I just mention it because it was one thing that I tried to get at the output.dir, but unsuccessfully.

  3. cderv commented on Apr 17, 2023

    @cderv
    Collaborator

    Vignettes are special use case of R Markdown rendering. Especially they are rendered in a package context, with specific rules regarding external resources.

    Let me give a generic feedback in this context

    The issue is that the image paths are not the same in these two use cases. In the former case, I want img.png, in the latter case I want vignettes/img.png.

    R Packages book has some recommandation on how to handle external file path, and the R-hub blog post some information about how to include external images with build vignette

    Your example is out of the package context, so probably the above not apply, but they will be important unless you correctly embed you image content in the output (the default with self_contained = TRUE I believe)

    Regarding your specific example now.

    Thanks for it. I can't really run it though because rprojroot::find_package_root_file() does not work outside of a package context.

    I see you are rendering a README from withing the vignette Rmd itself. This is not the best way IMO as you are using rmarkdown::render() from within an rmarkdown::render() - there will be some inherited context, and some possible side effect. I believe your path issues are also because of this.

    I understand from this that you want to use absolute filepath to image because of this specific nested usage on the same file. I think you should use rel_path = FALSE in include_graphics() (or options knitr.graphics.rel_path if you want to change more globally). As we document in the function's help page

    rel_path
    Whether to automatically convert absolute paths to relative paths. If you know for sure that absolute paths work, you may set this argument or the global option knitr.graphics.rel_path to FALSE

    Absolute paths are not recommended because depending on the output format, they will be used as is and it won't work correctly. Note that you could also compute the relative path yourself from an absolute path. You can use fs::path_rel() or xfun::relative_path().

    That being said, I think that using this specific patterns of nested render with some Rmd file in a nested structure, wanting to output in a parent directory is indeed difficult to handle image paths. I don't think that will be the only use case where it is difficult.

    Current workaround I have in mind

    • Use a parameter to pass your image path. You could even use inline markdown syntax like

       ![R logo](`r params$img_path`)

      You could then pass params in your render() call and change based on the file

    • You could compute yourself the relative path based on your idea, to not let knitr do it automatically (as it does not works for you)

    --- a/vignettes/not_portable.Rmd
    +++ b/vignettes/not_portable.Rmd
    @@ -8,7 +8,7 @@ vignette: >
    ---
    
    ```{r}
    -proj_root |>
    -    file.path("vignettes", "Rlogo.svg") |>
    -    knitr::include_graphics()
    +root_dir <- knitr::opts_knit$get("root.dir")
    +if (is.null(root_dir)) root_dir <- "."
    +file.path(proj_root, "vignettes", "Rlogo.svg") |>
    +    xfun::relative_path(dir = root_dir) |>
    +    knitr::include_graphics(error = FALSE)
    ```

    @multimeric does it helps ? Do you think that would work for you ?

    @yihui long discussion above, but in short

    In yihui/knitr@516b6f5 we are computing the relative path based on output.dir internal option, but this will not be coherent with output_dir from rmarkdown::render()

    Global idea here is : should output_dir from R Markdown be somehow taken into account for this include_graphics() auto trasnformation to relative path ?

    One workaround above is to compute relative path based on root.dir instead...

    Sharing in case you have ideas.

  4. yihui commented on Apr 17, 2023

    @yihui
    Collaborator

    Global idea here is : should output_dir from R Markdown be somehow taken into account for this include_graphics() auto trasnformation to relative path ?

    Yes, it sounds like a good idea to me to take rmarkdown's output_dir into account.

  5. added
    feature
    on Apr 17, 2023
  6. changed the title [-]`rmarkdown::render(output_dir=)` does not set `opts_knit$get("output.dir")`[/-] [+]`rmarkdown::render(output_dir=)` should be taken into account of `knitr::include_graphics()`[/+] on Apr 17, 2023
  7. multimeric commented on Apr 18, 2023

    @multimeric
    Author

    Thanks for it. I can't really run it though because rprojroot::find_package_root_file() does not work outside of a package context.

    Sorry, I forgot to commit the DESCRIPTION, this should be fixed now.

    I see you are rendering a README from withing the vignette Rmd itself. This is not the best way IMO as you are using rmarkdown::render() from within an rmarkdown::render() - there will be some inherited context, and some possible side effect. I believe your path issues are also because of this.

    I realise this is confusing, but this isn't what is happening. The cell that runs the render is set to eval=FALSE. It's just a mechanism to make it easy to build the vignette both ways:

    1. By pressing the knit button in RStudio, which will build it like a vignette
    2. By running this cell manually using the run button, which will build it into a readme

    I understand from this that you want to use absolute filepath to image because of this specific nested usage on the same file. I think you should use rel_path = FALSE in include_graphics() (or options knitr.graphics.rel_path if you want to change more globally). As we document in the function's help page

    Correct me if I'm wrong, but I don't think this is true. When knitting to GitHub markdown, I absolutely want the paths to be relative, because the relative paths need to be turned into relative URLs so they work on the GitHub readme page.

    Use a parameter to pass your image path. You could even use inline markdown syntax like

    I don't think this makes sense, because then I would have to pass in all the image paths, for each configuration I knit. I want one setting that changes all images. One solution similar to this is to pass in an "image root" as a parameter which all images are made relative to. Then you just set out.dir to equal params$image_root. But at that point I would prefer a mechanism to just set the out.dir directly.

    You could compute yourself the relative path based on your idea, to not let knitr do it automatically (as it does not works for you)

    This might work, not sure, but it's complex, and it would be nicer to utilise knitr's existing relative path rewriting functionality here instead of working around it.

  8. added
    next
    on Apr 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurenext

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions