将 R 降价参数传递给源 R 脚本

Passing R markdown parameters to a sourced R script

我有一个闪亮的应用程序,用户可以在其中 select 传递给参数化 R 降价报告的选项。然后,Rmd 获取一系列 R 脚本来提取和汇总数据,为报告创建绘图等。

我用来提取数据的脚本包括一个参数化的 SQL 查询,它继承了 R markdown params 的值(又继承自 Shiny input ).但是,整个过程此时停止,我收到一条错误消息,指出 params 不存在。

我相当确定将输入从 Shiny 传递到 R markdown 参数工作正常 - 所以问题似乎是将它们传递到源脚本(​​注意:它只是一个 R 脚本,而不是一个函数) .我猜这与脚本在获取源代码时访问的环境有关(尽管它使用了在 R markdown 中的前一个块中生成的数据库连接而没有问题)——但除此之外,有点迷失了如何纠正这个。任何想法将不胜感激。

这是闪亮的应用程序:

##########################################
# SHINY APP - USER INTERFACE:

ui = fluidPage (
    selectInput("pathogen", "Enter pathogen of interest:", c("Campylobacter" = "Campylobacter", "Escherichia" = "Escherichia",
                "Salmonella" = "Salmonella", "Shigella" = "Shigella"), selected = "Salmonella" ),

    radioButtons("pkginstall", "Install required packages?",  c("Yes" = "yes", "No" = "no"),selected = "yes"),

    downloadButton("report", "Generate report")
)


##########################################
# SHINY APP - SERVER LOGIC:

#fileInput("download_location","Select File Location"),
server = function(input, output) {
    # Create the output: 
    output$report = downloadHandler(

      filename = paste0("Pathogen Report ", input$pathogen, "_", format(Sys.time(),"%d-%b-%Y %H.%M"), ".html"),

      content = function(file) {

        # Copy the .Rmd to a temporary directory:
        tempReport <- file.path(tempdir(), "Pathogen_Report.Rmd")
        file.copy("Pathogen_Report.Rmd", tempReport, overwrite = TRUE)


        # Set up parameters to pass to Rmd document:
        params <- list(pathogen = input$pathogen, pkginstall = input$pkginstall)

        # Define name of report:
        outname <- paste0("Pathogen Report ", input$pathogen, "_", format(Sys.time(),"%d-%b-%Y %H.%M"), ".html") 

        # Knit the document:
        created_filename <- rmarkdown::render(input = tempReport, 
                          output_file = outname, 
                          params = params,
                          envir = new.env(parent = globalenv())
                          )
        file.rename(created_filename, file)
      }
    )
  }

##########################################
# SHINY APP - RUN:

# Run app:
shinyApp(ui =ui, server=server)

##################################################################

这里是 R markdown YAML header:

---
params:
  pathogen: 
    label: "Enter pathogen of interest:" 
    value: Shigella
    input: select
    choices: [Campylobacter, Escherichia, Salmonella, Shigella]
title: "Pathogen Report"
date: "`r format(Sys.time(), '%d %B %Y')`"
output: 
  phecharts::html_phe:
    includes:
      in_header: phe_logo.html
---

以及采购 R 脚本的相关块:

{r, GDW Query, echo=FALSE, cache=FALSE, message=FALSE, warning=FALSE, results='hide'}
####################################################################
# QUERY DATABASE AND EXTRACT DATA 

source("Extract_data.R")

Extract_data.R 包含一个 SQL 查询,其中应该用病原体名称替换从 R markdown 参数继承的名称:

# Example SQL to PostgreSQL database:
query <- "SELECT * FROM table1 WHERE table1.organism ~ '^@pathogen'"

# Substituting pathogen for pathogen name from R markdown parameters:
query <- gsub("@pathogen", params$pathogen, query)

# Executing the query:
mydata <- data.table(RPostgres::dbGetQuery(conn = dbcon, statement = query))

请注意,通过在此之前的 R markdown 块中获取另一个脚本,已成功建立数据库连接。

这是我得到的错误:

Quitting from lines 84-88 (Pathogen_Report.Rmd) 

Warning: Error in gsub: object 'params' not found
  [No stack trace available]

查看 source (?source) 中的参数 local

local TRUE, FALSE or an environment, determining where the parsed expressions are evaluated. FALSE (the default) corresponds to the user's workspace (the global environment) and TRUE to the environment from which source is called.

直接渲染Rmd时,params是默认设置的,你是在全局环境中。所以这会起作用:

---
params:
  pathogen: 
    label: "Enter pathogen of interest:" 
    value: Shigella
    input: select
    choices: [Campylobacter, Escherichia, Salmonella, Shigella]
  pkginstall:
    value: no
title: "Pathogen Report"
date: "`r format(Sys.time(), '%d %B %Y')`"
output: html_document
---

```{r GDW Query, echo=TRUE, cache=FALSE, message=FALSE, warning=FALSE, results='hide'}
####################################################################
# QUERY DATABASE AND EXTRACT DATA 
source(Extract_data.R, local=FALSE) # same as source(Extract_data.R)

但是,当 运行 Rmd 通过 Shiny App 你想在 Shiny 工作的环境中工作,并且你想获取外部脚本就像它被粘贴在一行中一样(参见 https://shiny.rstudio.com/articles/scoping.html)。以下应该有效:

---
params:
  pathogen: 
    label: "Enter pathogen of interest:" 
    value: Shigella
    input: select
    choices: [Campylobacter, Escherichia, Salmonella, Shigella]
  pkginstall:
    value: no
title: "Pathogen Report"
date: "`r format(Sys.time(), '%d %B %Y')`"
output: html_document
---

```{r GDW Query, echo=TRUE, cache=FALSE, message=FALSE, warning=FALSE, results='hide'}
####################################################################
# QUERY DATABASE AND EXTRACT DATA 
source(Extract_data.R, local=TRUE)