Skip to content

Instantly share code, notes, and snippets.

Last active Apr 23, 2018
What would you like to do?
A function that allows the arguments in function calls to be self-referential.
#' Allow self-referential arguments in functions.
#' @param call A function call.
#' @param quote Logical; if \code{TRUE}, the supplied \code{call} is interpreted
#' as a quote, so \code{substitute} is applied.
#' @return The evaluated function call with the self-refering arguments
#' evaluated.
#' @examples
#' R(plot(y = 1:10, x = y^2))
#' R(plot(x = y^2, y = 1:10))
#' R(plot(x = 1:10, y = x^2, xlab = x, ylab = y, main = xlab))
#' simulated = R(data.frame(y = 2*x1 + 3*x2 + rnorm(100),
#' x1 = rnorm(100),
#' x2 = rnorm(100)))
R = function(call, quote = TRUE) {
call = if(quote) substitute(call) else call
args = as.list(call)[-1]
e = new.env()
for(arg in names(args)), list(arg, args[[arg]], e, e))[[1]]), as.list(e))

This comment has been minimized.

Copy link
Owner Author

@JonasMoss JonasMoss commented Apr 23, 2018

A problem with the function is that it evaluates each argument as part of "as.list(promise)". This is ""-like behaviour, which goes counter to expectations in some problems. For instance, R(plot(x = y^2, y = 1:10)) whill show c(1, 4, 9 ...) on the x-axis instead of the quote y^2. Usually this isn't a big problem, but I'd like better behaviour than that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment