如何检查一个函数是否是R工作空间中的对象,如果不是,运行源文件来调用它?



在下面的示例代码中,函数testFunction()在保存在桌面上的单独源文件functionsLibrary.R中定义。此示例代码按预期工作。

我如何修改代码以首先测试testFunction()是否是R工作区中的对象,并且仅当时才将其源(运行source("C:/Users/laran/OneDrive/Desktop/functionsLibrary.R")行)函数不在工作空间中?

在完整的代码中,这是为了,该函数需要很长时间来运行(读取大数据文件到内存),我只希望它的来源,如果它目前不是一个工作空间对象。

示例代码:

library(shiny)
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)

源文件内容(文件名functionsLibrary.R):

testFunction <- function(a) {
b <- data.frame(Value=seq(1:a),Square_Value = seq(1:a)^2)
return(b)
}

一个简单的方法是使用exist()。这应该可以解决你的问题。

library(shiny)
if (!exists("testFunction")) {
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)

我们可以扩展if子句来检查testFunction是否真的是一个函数,如果它存在,则source为文件。

if (!exists("testFunction") || (exists("testFunction") && !is.function(testFunction)))

相关内容

最新更新