The Magic of Substitute and Deparse

Master R

By Guangming Lang Comment

The R functions substitute() and deparse() are very interesting and here’s why.

foo1 = function(a, ...) {
        arg = deparse(substitute(a))
        dots = substitute(list(...))[-1]
        c(arg, sapply(dots, deparse))
}

foo2 = function(a, ...) {
        arg = deparse(substitute(a))
        dots = list(...)
        c(arg, sapply(dots, deparse))
}

x = 1; y = 2; z = 3

foo1(x, y, z)
## [1] "x" "y" "z"
foo2(x, y, z)
## [1] "x" "2" "3"

You can learn more about them here and here.

If you enjoyed this post, get updates. It's FREE