如何使用 R Rmarkdown 文件中的函数内部变量,使用渲染

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

我有一个用 rmarkdown::render 编写的 rmarkdown 文件:我在 .R 中进行了所有数据处理,然后,我使用函数在 Rmd 中编写。我的问题是,如果我封装渲染函数以使我的代码更具可读性,它就不再起作用了。这是一个基本示例: - 我的 .Rmd 文件:

---
title: "test"
output: html_document
---

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

我的 R 代码有效:

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

但是当我将它封装在一个函数中时,它就不再起作用了:

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

rendre()

对于这段代码,我有一个非常明显的错误:Quitting from lines 7-8 Error in printA() : object 'a' not found

如果我明确地为 printA 函数添加一个参数,这个问题将很容易解决,在这种情况下这无论如何都是一个很好的做法,但我不明白为什么它在这两种情况下的工作方式不同。

你的问题更多的是函数 printA 没有在你的 rendre() 函数中声明。 (即使错误消息提到 a)。因此,您可以在 rendre()Rmd 文件中声明您的函数。

rendre() 函数内部

rendre <- function(){
  printA <- function() {
    return(a)
  }
  a <- 5
  render("c:/users/db7trs/desktop/test.Rmd")
}

OR 在 test.Rmd

---
title: "test"
output: html_document
---

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