Constructing a function manually in R
Asked Answered
S

1

11

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?

Schindler answered 4/6, 2014 at 17:7 Comment(5)
Is this question helpful at all?Jodi
I was hoping to directly use the primitive function `function` as I believe this is what R evaluates when constructing a funcion.Schindler
Look at make_function4 in the answer I linked to, I think that's the version you're referring to.Jodi
You may find the chapter at adv-r.had.co.nz/Functions.html useful.Trinh
no idea what your goal is but I'd start thinking about proper class definitions. I think your control structures could just be methods.Sequoia
S
1

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}
Storyteller answered 24/2, 2015 at 3:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.