如何在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
相关产品推荐
相关产品推荐

