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

如何在R工作区检测函数是否存在,仅缺失时执行source导入?

解决方案

你可以通过 exists() 函数检测工作区中是否存在目标函数,仅当函数不存在时执行 source() 操作。修改后的完整代码如下:

library(shiny)

# 仅当testFunction不存在时才导入源文件
if (!exists("testFunction", mode = "function")) {
  source("C:/Users/laran/OneDrive/Desktop/functionsLibrary.R")
}

ui <- fluidPage(
  br(),
  numericInput('selectValue','Select number of values to square:',value=1,step=1,min=1),
  br(),
  tableOutput('table')
)

server <- function(input,output,session)({
  output$table <- renderTable(testFunction(input$selectValue))
})

shinyApp(ui, server)

说明:

  • exists("testFunction", mode = "function") 会检查工作区中是否存在名为 testFunction 的函数对象,指定 mode="function" 可以避免与同名变量混淆。
  • 逻辑非运算符 ! 反转判断结果,确保只有当函数不存在时才执行 source() 语句,避免重复加载耗时的大型数据文件。

内容的提问来源于stack exchange,提问作者Village.Idyot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:05:47