I was reading the book Advanced R and confused with the concept of "escape hatch" repeatedly mentioned in the chapter on Non-standard evaluation. For example, the first time the author mentioned this word, it has the following definition:
As a developer, you should always provide an escape hatch: an alternative version of the function that uses standard evaluation.
It also has some examples about the escape hatch. One of the example is from the part Calling from another function. The author said:
Typically, computing on the language is most useful when functions are called directly by users and less useful when they are called by other functions.
See the code of the example below:
sample_df <- data.frame(a = 1:5, b = 5:1, c = c(5, 3, 1, 4, 1))
subset2 <- function(x, condition) {
condition_call <- substitute(condition)
r <- eval(condition_call, x, parent.frame())
x[r, ]
}
scramble <- function(x) x[sample(nrow(x)), ]
subscramble <- function(x, condition) {
scramble(subset2(x, condition))
}
But it doesn’t work:
subscramble(sample_df, a >= 4)
# Error in eval(expr, envir, enclos) : object 'a' not found
traceback()
#> 5: eval(expr, envir, enclos)
#> 4: eval(condition_call, x, parent.frame()) at #3
#> 3: subset2(x, condition) at #1
#> 2: scramble(subset2(x, condition)) at #2
#> 1: subscramble(sample_df, a >= 4)
The author said we could write a version of subset2() that takes an already quoted expression in this case. Codes are showed below:
subset2_q <- function(x, condition) {
r <- eval(condition, x, parent.frame())
x[r, ]
}
subset2 <- function(x, condition) {
subset2_q(x, substitute(condition))
}
subscramble <- function(x, condition) {
condition <- substitute(condition)
scramble(subset2_q(x, condition))
}
Then it runs well:
subscramble(sample_df, a >= 3)
#> a b c
#> 4 4 2 4
#> 5 5 1 1
#> 3 3 3 1
subscramble(sample_df, a >= 3)
#> a b c
#> 5 5 1 1
#> 3 3 3 1
#> 4 4 2 4
Even though the author gives me the example, I still do not understand the escape hatch. So, can someone explain its definition in this book or in R programming language? My sessionInfo:
sessionInfo()
R version 3.5.0 (2018-04-23)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
Matrix products: default
locale:
[1] LC_COLLATE=Chinese (Simplified)_People's Republic of China.936
[2] LC_CTYPE=Chinese (Simplified)_People's Republic of China.936
[3] LC_MONETARY=Chinese (Simplified)_People's Republic of China.936
[4] LC_NUMERIC=C
[5] LC_TIME=Chinese (Simplified)_People's Republic of China.936
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] compiler_3.5.0 tools_3.5.0 yaml_2.2.0