Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emulate Lisp's let function in R?

I'm trying to write a let function that allows me to do things like:

let(a=2, b=3, a+b)
>>> 5

Currently I'm stuck with

let <- function(..., expr) {
  with(list(...), quote(expr))
}

which doesn't work at all. Any help appreciated.

like image 525
Ernest A Avatar asked Oct 14 '25 07:10

Ernest A


1 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 don't want to have to name the expression-to-be-evaluated (i.e. passing it in via expr), and if you are certain that it will always be the last argument, you could 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
like image 121
Josh O'Brien Avatar answered Oct 18 '25 02:10

Josh O'Brien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!