RMarkdown - How can you check whether the current running script is the main or a child document?

rstudioapi does not work to get the current file name.

You can to know if the current render Rmd is the main document or a child document ? Is that so ?

Do you have an example so that it helps clearly understand. Thank you !

yes! That's my question.

Let's assume I have a main .Rmd document

---
output:
  pdf_document: default
  html_document: default
---

#```{r, child=c('child1.Rmd')}
#```

and a child document called child1.Rmd .

plot(x)

I want to provide objects generated in one file, let's call it setup.Rmd to each child .Rmd script such that each child can be standalone with the setup.Rmd being

x <- rnorm(100)

a possible other child2.Rmd could be

plot(x, type = "p")

I'd like to include the setup.Rmd to a child with

#```{r, child=c('setup.Rmd')}
#```

If I could get the name of the current script the child could be

#```
# filename <- ???
#```
#```{r, if (filename) child=c('setup.Rmd')}
#```

If it would run within RStudio you could extract the filename with rstudioapi::getActiveDocumentContext()$path

But there must be another solution.

This may be kind of a trick but with knitr, you can check this internal option opts_knit$get("child").
It will be set to TRUE when a child is running.
So if the Rmd is rendered as a child document, it will be true, otherwise false.
This is only to read - You should not modify this option !

About the filename of the file being knitted, take a look at knitr::current_input()

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.