How do I emulate the Lisp let function in R?
2 answers
Here's one way:
let <- function(..., expr) {
expr <- substitute(expr)
dots <- list(...)
eval(expr, dots)
}
let(a = 2, b = 3, expr = a+b)
# [1] 5
Edit . Alternatively, if you do not want to specify an expression to evaluate (i.e. pass it through expr
), and if you are sure that this will always be the last argument, you can do something like this.
let <- function(...) {
args <- as.list(sys.call())[-1]
n <- length(args)
eval(args[[n]], args[-n])
}
let(a = 2, b = 3, a + b)
# [1] 5
+11
source to share