Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing a function manually in R

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?

like image 728
Jon Claus Avatar asked Jun 04 '14 17:06

Jon Claus


1 Answers

This will not be prompt answer but I just tried to focus on your function call.

Just try this code:

   as.list((substitute(function(x = 1, a) {x + a})))
   [[1]]

    `function`

  [[2]]

  [[2]]$x

  [1] 1

  [[2]]$a

  [[3]]
   {
      x + a
    }
 [[4]]
      function(x = 1, a) {x + a}
like image 180
Leeya Avatar answered Sep 22 '22 08:09

Leeya