Tuesday 1 July 2014

Metaprogramming in R

Cited from Metaprogramming

quote() returns an expression: an object that represents an action that can be performed by R (Unfortunately expression() does not return an expression in this sense. Instead, it returns something more like a list of expressions. For example,
z <- quote(y <- x * 10)


str() describes names as symbols and calls as language objects. For example,
str(quote(a))
str(quote(a + b))

To create a new call from its components, you can use call() or as.call(). The first argument to call() is a string which gives a function name. The other arguments are expressions that represent the arguments of the call. For example,
call(":", 1, 10)
call("mean", quote(1:10), na.rm = TRUE)

as.call() is a minor variant of call() that takes a single list as input. The first element is a name or call. The subsequent elements are the arguments. For example,
as.call(list(quote(mean), quote(1:10)))

Many base R functions use the current call: the expression that caused the current function to be run. There are two ways to capture a current call:
sys.call() captures exactly what the user typed.
match.call() makes a call that only uses named arguments. It’s like automatically calling pryr::standardise_call() on the result of sys.call().



No comments:

Post a Comment