You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Shiny应用UI端用户输入传递至被source的R脚本

How to Pass Shiny Input Variables to a Sourced External R Script

The core issue here is that when you use source() without specifying the local parameter, it runs the script in the global environment—but your foo variable is defined inside the local environment of the renderDataTable function. That's why the external script can't find it. Here are two reliable fixes:

Fix 1: Run the sourced script in the local environment

Modify your source() call to include local = TRUE, which tells R to execute the script in the current (local) environment where foo exists:

library(shiny)
library(DT)
ui <- fluidPage(
  checkboxInput("somevalue", "Check box", FALSE),
  dataTableOutput("table1")
)
server <- function(input, output) {
  output$table1 <- renderDataTable({
    foo <- input$somevalue
    # Execute the script in the current local environment
    source("~/path/to/file/test.R", local = TRUE)
    df
  })
}
shinyApp(ui, server)

Your external test.R can stay exactly as it is:

df = data.frame("Is the check box checked?" = foo, check.names = F)

A cleaner, more maintainable approach is to turn your external script into a function that accepts foo as a parameter. This avoids environment-related confusion entirely.

Update test.R to define a function:

create_checked_df <- function(foo) {
  data.frame("Is the check box checked?" = foo, check.names = FALSE)
}

Then call this function in your Shiny app (you can source the function once at the top of the server logic instead of inside the render call for efficiency):

library(shiny)
library(DT)
ui <- fluidPage(
  checkboxInput("somevalue", "Check box", FALSE),
  dataTableOutput("table1")
)
server <- function(input, output) {
  # Source the function once when the server starts
  source("~/path/to/file/test.R")
  
  output$table1 <- renderDataTable({
    foo <- input$somevalue
    # Call the function with your Shiny input variable
    df <- create_checked_df(foo)
    df
  })
}
shinyApp(ui, server)

Why your original code failed

By default, source() uses local = FALSE, meaning it runs code in the global workspace. Since foo is only defined inside the renderDataTable closure (a local environment), the global environment has no knowledge of it—hence the "object foo not found" error.

内容的提问来源于stack exchange,提问作者chilifan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 07:39:09