1

This seems like a very basic question, but somehow I cannot find the solution anywhere. I am trying to pass variables to R markdown child documents.

In the parent document, I have this chunk:

```{r}
var1 = "test-var1!"
cat(knit_child("child.Rmd"), sep = "\n")
```

In the child document, if I use ls(), I can see var1 is in the environment. However, if I try to use var1, I get a knit error:

Error in str(var1) : object 'var1' not found
Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> str

I tried knitting in RStudio and on the command line.

Is there a way to use objects in the child document?

burger
  • 5,683
  • 9
  • 40
  • 63
  • If there's not a way for the child doc to pull a variable from parent's global variable, consider passing the value to the child as a report parameter: http://rmarkdown.rstudio.com/developer_parameterized_reports.html#using_parameters – wibeasley Nov 27 '17 at 18:12
  • Also, the conventional way of specifying a knitr child document might open up other approaches. Try either (a) https://yihui.name/knitr/demo/child/ or (b) https://rdrr.io/cran/knitr/man/knit_child.html with then 'envir' argument set to `parent.frame()`. – wibeasley Nov 27 '17 at 18:14
  • relevant: https://stackoverflow.com/questions/34498734/how-do-you-hide-and-pass-variables-in-knitr-child-documents – user5359531 Nov 27 '17 at 18:59

1 Answers1

2

I have created a MWE with two defaults files form RStudio and I cannot reproduce your error, though I guess the ouput is not the one you are looking for.

Parent.Rmd file:

---
title: "Parent"
author: "Clement Walter"
date: "27/11/2017"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r}
var = 1
cat(knitr::knit_child("Child.Rmd"), sep = "\n")
```

Child.Rmd file:

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r}
ls()
var + 1
```

Output : MWE

ClementWalter
  • 4,814
  • 1
  • 32
  • 54
  • 1
    Thanks for confirming. Upon further inspection, it turns out it was a dumb mistake. I was actually calling child.Rmd earlier in my code thinking it was a different child. – burger Nov 27 '17 at 21:17