Skip to content

Instantly share code, notes, and snippets.

@JonasMoss
Last active April 23, 2018 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonasMoss/c1f6fed4e09d65ab93917208a97a7066 to your computer and use it in GitHub Desktop.
Save JonasMoss/c1f6fed4e09d65ab93917208a97a7066 to your computer and use it in GitHub Desktop.
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)) do.call(delayedAssign, list(arg, args[[arg]], e, e))
do.call(deparse(call[[1]]), as.list(e))
}
@JonasMoss
Copy link
Author

A problem with the function is that it evaluates each argument as part of "as.list(promise)". This is "do.call"-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