如何将Shiny应用UI端用户输入传递至被source的R脚本
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)
Fix 2: Convert the script to a function (recommended for better practice)
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

