7

有人可以为我提供一个简单的用例,其中 on.exit() 函数的“add”参数为真?

4

2 回答 2

10

这是一个非常简单的例子

myfun <- function(x){
    on.exit(print("first"))
    on.exit(print("second"), add = TRUE)
    return(x)
}

myfun(2)
#[1] "first"
#[1] "second"
#[1] 2

还要注意没有 add=TRUE 参数会发生什么

fun <- function(x){
    on.exit(print("first"))
    on.exit(print("second"))
    return(x)
}

fun(2)
#[1] "second"
#[1] 2

如果您不添加“add=TRUE”,则对 on.exit 的第二次调用将删除第一次调用。

于 2012-06-11T01:20:28.860 回答
0

我不知道 R 但阅读onexeit 的定义add = true确保除了任何先前存储的 onexit experssions 之外,还评估第一个表达式,同时add = false覆盖前一个表达式。

所以环顾四周,我在jhsph.edu上找到了这个:

它似乎基本上确保它tmp也关闭以及 file退出

readData2 <- function(file, ...) {
        file <- file(file, "r")
        on.exit(close(file))

        tmp <- tempfile()
        tmpcon <- file(tmp, "w")

        on.exit(close(tmpcon), add = TRUE)

        incomment <- FALSE

        while(length(line <- readLines(file, 1)) > 0) {
                .
                .
                . ommited in SO example
                .
                .
                .
        }
        close(tmpcon)
        close(file)
        on.exit()

        read.csv(tmp, ...)
}
于 2012-06-11T00:44:57.153 回答