R编程:在tryCatch块之间共享变量

时间:2019-07-16 16:26:27

标签: r scope try-catch

我有一个昂贵的函数,需要使用不同的数据集运行“ K”次,这是在parLapply循环中完成的。有时,该代码会发出警告;我需要输出和警告。有时该代码会发出错误,这会引起问题,因为我需要不停止parLapply循环;所以我正在使用tryCatch进行错误处理。我遇到了警告块的问题:引发警告时,有问题的代码将停止执​​行,并且感兴趣的变量只能在try块中访问,而我不能从警告块中返回它。

我一直在尝试寻找在块之间共享数据的方法,但是我一直没有成功。我看到了将变量从全局环境获取到try-catch块中的方法,但没有通过。这是一个功能代码,解释了我要做什么以及不足之处。

'''
loadData <- function(index){
    # load large data file, but returning 1 for minimal working code
    # return(read.csv(sprintf("./filename%d.csv", index)))
    return (1)
}

expensiveFunction <- function(dataset, index){
    if (index == 1){
    } else if (index == 2){
            dir.create("./tempFolder")
            # try to create the same folder name, which generates a 
warning
            dir.create("./tempFolder")
            unlink("./tempFolder")  # delete the folder
    } else if (index >= 3){
            # call undefined function to generate a 
            undefinedFunction(1, 2, 3)
    }
    print("am I making it past the error/warning generation?")
    return(2*dataset) # imagine this takes 30 minutes to run
}

analysis <- function(index){
    result <- tryCatch({
            data <- loadData(index)
            output <- expensiveFunction(data, index)
            return(output)
    }, warning = function(w){
            print(sprintf("Warning was thrown: %s", w))
            return(output)
    }, error = function(e){
            print(sprintf("Skipping iteration: Error was thrown: %s", e))
            return(NaN)
    }, finally = {}
    )
}

aa <- lapply(1:3, analysis)
print(aa[[1]])
print(aa[[2]])
print(aa[[3]])
'''

预期结果:

"am I making it past the error/warning generation?"
"Warning was thrown: simpleWarning in dir.create(\"./tempFolder\"): '.\\tempFolder' already exists\n"
"am I making it past the error/warning generation?"
"Skipping iteration: Error was thrown: Error in undefinedFunction(1, 2, 3): could not find function \"undefinedFunction\"
2
2
NaN

实际结果:

> aa <- lapply(1:3, analysis)
[1] "am I making it past the error/warning generation?"
[1] "Warning was thrown: simpleWarning in dir.create(\"./tempFolder\"): '.\\tempFolder' already exists\n"
[1] "Skipping iteration: Error was thrown: Error in value[[3L]](cond): object 'output' not found\n"
[1] "Skipping iteration: Error was thrown: Error in undefinedFunction(1, 2, 3): could not find function \"undefinedFunction\"\n"
> print(aa[[1]])
[1] 2
> print(aa[[2]])
[1] NaN
> print(aa[[3]])
[1] NaN

阅读文档后,我认为该功能与预期的一样。但是我不知道如何强迫它做我想要的事情。

0 个答案:

没有答案