Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 880
Malta Avatar asked Oct 21 '25 11:10

Malta


1 Answers

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()
```
like image 178
Sébastien Rochette Avatar answered Oct 23 '25 00:10

Sébastien Rochette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!