-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.