As a symptom of R being a functional language, it is possible to specify many control structures using pure functional notation. For example, an if statement:
> as.list((substitute(if(a == 1) 1 else 2)))
[[1]]
`if`
[[2]]
a == 1
[[3]]
[1] 1
[[4]]
[1] 2
> as.list(substitute(`if`(a == 1, 1, 2)))
[[1]]
`if`
[[2]]
a == 1
[[3]]
[1] 1
[[4]]
[1] 2
Out of curiosity I attempted to do the same for a function definition. Functions are typically constructed using the function(args) body
syntax but there also exists a function named function
in R. The problem I ran into is that the un-evaluated definition of a function will contain a pairlist:
> substitute(function(x = 1, a) {x + a})[[2]]
$x
[1] 1
$a
[empty symbol]
The second argument is a pairlist between the names of the arguments and there default values, which are possibly empty symbols. As far as I know, it is impossible to pass a list or a pairlist as part of expression using only manual calls. Below are my attempts:
> substitute(`function`(x, {x + 1}))
Error: badly formed function expression
> substitute(`function`((x), {x + 1}))
function(`(`, x) {
x + 1
}
If I pass a single symbol as the second argument to `function`
, an error is thrown (and this wouldn't work for a function with multiple arguments). When passing a call as the second argument, the call appears to be coerced to a list upon being parsed.
This can be abused by using the first argument as the name of the call:
> substitute(`function`(a(x), {x + 1}))
function(a, x) {
x + 1
}
However, the call is not actually converted to a pairlist and only appears to be so. When evaluating this expression, an error is thrown. It would be ideal to somehow insert a list / pairlist into the result of a call to substitute. Does anyone know how to do so?
`function`
as I believe this is what R evaluates when constructing a funcion. – Schindlermake_function4
in the answer I linked to, I think that's the version you're referring to. – Jodi