Q:

How to use a variable inside a function in a R Rmarkdown file, using render

I have a rmarkdown file I knit with rmarkdown::render : I make all my data processing in the .R and then, I knit in a Rmd using function. My problem is, if I encapsulate the render function in order to make my code more readable, it doesn't work anymore. Here is a basic example :
- My .Rmd file :
---
title: "test"
output: html_document
---

```{r}
printA()
```

My R Code that work :
library(rmarkdown)
a<- 5
printA <- function() {
  return(a)
}
render("c:/users/db7trs/desktop/test.Rmd")

but when I encapsulate that in a function, that doesn't work anymore :
library(rmarkdown)
printA <- function() {
  return(a)
}
rendre <- function(){
  a <- 5
  render("c:/users/db7trs/desktop/test.Rmd")
}

rendre()

With this code, I have a quite explicit error : Quitting from lines 7-8 Error in printA() : object 'a' not found. 
This problem would be easily solved if I explicitly make a an argument of the printA function, which in this case would anyway be a good practice, but I don't understand why it works differently in this two cases.

A:

Your problem is more that the function printA is not declared inside your rendre() function. (Even if the error message speaks about a). Hence, you can declare your function inside rendre() or inside the Rmd file.  
Inside rendre() function
rendre <- function(){
  printA <- function() {
    return(a)
  }
  a <- 5
  render("c:/users/db7trs/desktop/test.Rmd")
}

OR inside the test.Rmd
---
title: "test"
output: html_document
---

```{r}
printA <- function() {
  return(a)
}
printA()
```

