我开发了一个 Shiny 的应用程序,它显示一些动态图表。这些图表是在执行时根据某些按钮的值生成的。这个 Shiny 的应用程序从之前经过处理和转换的原始 csv 中获取数据。除了 Shiny 的应用程序之外,我还得到了一个 Rscript 来对原始数据进行所有这些“转换”。我想做的是从 Shiny 的应用程序调用此 Rscript,以便在 Shiny 的应用程序启动时执行。
我已经检查过这些链接,但根本没有帮助:How can I connect R Script with Shiny app in R?还有这个using Source() in Shiny 。我也检查了 Rstudio 文档:http://shiny.rstudio.com/tutorial/lesson5/ .
我认为它应该是这样的,即 procesadoDatos.R RScript。我只想在开始时执行源命令,以便在 Shiny 的应用程序启动时加载数据:
source("procesadoDatos.R",local = TRUE)
shinyServer(function(input, output,session) {
(renderplots, reactives elements and so on)}
Rscript 是作为 server.R 和 UI.R 文件的 Shiny 项目路径。我也尝试过包含路径,但它也不起作用。
我尝试的另一件事是创建一个函数来进行所有转换,然后在获取它之后从 server.R 文件中调用它:
source("procesadoDatos.R",local = TRUE)
generate_data(ticketsByService_report10.csv)
正在RScript中定义generate_data这个函数:
generate_data <- function(csv_file) {
(all those transformation, data frame an so on)}
在所有情况下,我都收到相同的错误,指出未找到 RScript 中生成的数据帧。
有人知道这是怎么回事吗?提前致谢
最佳答案
Shiny 的范围
所有这些很大程度上取决于您调用 source()
的具体位置。如果您需要从 UI 和服务器功能中查找数据,请将 source()
放在应用程序之外。
如果将 source()
放置在服务器函数内,UI 将无法找到脚本创建的任何对象。如果将其放入渲染函数内,则对象仅在该渲染函数内可见。另请参阅Scoping rules for Shiny
注意,如果您有单独的 server.R 和 ui.R 文件,并且希望 UI 查找脚本创建的对象,则应添加 global.R
文件复制到您的应用程序目录。然后,source()
命令进入 global.R
文件。
一个小例子:
source('testScript.R')
shinyApp(
fluidPage(
selectInput("cols", "pick columns",
choices = names(x)),
dataTableOutput("what")),
function(input, output, session){
output$what <- renderDataTable(x)
}
)
和testScript.R
包含一行:
x <- iris
这里的关键是:
- 脚本实际上必须创建这些对象
- 脚本应源自正确的位置。
因此,如果您可以执行以下操作:
shinyApp(
fluidPage(
selectInput("cols", "pick columns",
choices = names(x)),
dataTableOutput("what")),
function(input, output, session){
source('testScript.R', local = TRUE)
output$what <- renderDataTable(x)
}
)
您收到有关无法找到 x
的错误。这是正常的,因为 x
现在仅在服务器函数的环境中定义。
不过你仍然可以这样做:
shinyApp(
fluidPage(
dataTableOutput("what")),
function(input, output, session){
source('R/testScript.R', local = TRUE)
output$what <- renderDataTable(x)
}
)
请注意 x
仅在服务器函数内部需要,而不是在 UI 内部。
使用函数
对于函数,同样的情况也适用。您将函数定义放入脚本中并像以前一样获取它。函数只不过是一个对象,因此脚本本质上创建了一个函数对象,然后可以使用完全相同的作用域规则找到该对象。
请记住,如果您想使用函数的结果,则该函数应该返回一些内容。因此,将这个简单的示例放入 testScript.R
中:
myfun <- function(x){
tmp <- iris[x]
return(tmp)
}
现在您可以执行以下操作:
source('testScript.R', local = TRUE)
shinyApp(
fluidPage(
selectInput("cols", "pick columns",
choices = names(myfun())),
dataTableOutput("what")),
function(input, output, session){
output$what <- renderDataTable(myfun(input$cols))
}
)
如果您将 source() 放在服务器函数中,这将不再起作用。 UI 端将无法再看到 myfun()
。
rm(list = ls())
shinyApp(
fluidPage(
selectInput("cols", "pick columns",
choices = names(myfun())),
dataTableOutput("what")),
function(input, output, session){
source('R/testScript.R', local = TRUE)
output$what <- renderDataTable(myfun(input$cols))
}
)
# Error in myfun() : could not find function "myfun"
关于r - 从 Shiny App 调用 R 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44524619/