3

in R pretty much everything that is not a variable of another type is a function.

It seems that function itself is one :

`function`
# .Primitive("function")

Though I'm not sure, it doesn't return the same thing as say + :

`+`
# function (e1, e2)  .Primitive("+")

It seems it's possible to call it though :

formals(`function`)
# NULL
`function`(x)
# Error: incorrect number of arguments to "function"
`function`(x,y)
# Error: invalid formal argument list for "function"
`function`(x,y,3,4,5,6,7,8,9,10)
# Error: invalid formal argument list for "function"

How (if possible at all) could we define a simple function such as this one:

plus <- function(x,y) x+y

Here's what I tried:

plus <- `function`(x,y,expression(x+y))
# Error: invalid formal argument list for "function"

Before you ask, I'm just curious, I don't have any practical use case in mind.

moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
  • In the little time playing around/searching, the closest thing I've found to what you're asking that works is calling `function` with `call` as opposed to directly calling the backquoted `` `function` ``. This is shown in joran's answer [here](https://stackoverflow.com/a/12983961/5731525). – Adam Spannbauer Feb 15 '18 at 13:29
  • 1
    maybe you want to read the R internals manual, in particular section 2: https://cran.r-project.org/doc/manuals/r-release/R-ints.html#g_t_002eInternal-vs-_002ePrimitive – RolandASc Feb 15 '18 at 13:39
  • Thanks to Adam and Joran I can do this `plus <- eval(call("function",as.pairlist(alist(x=NULL,y=NULL)),quote(x+y)))` and it works: `plus(3,4)`. I must give a value to `x` and `y` though, and `'function'(as.pairlist(alist(x=NULL,y=NULL)),quote(x+y))` still doesn't work. – moodymudskipper Feb 15 '18 at 13:47
  • Thank Roland it looks really interesting – moodymudskipper Feb 15 '18 at 13:48
  • @Artem, definitely very related! Not sure if it's a complete duplicate. What do you think @Moody? – Axeman Sep 06 '18 at 22:20
  • Sorry to be a buzzkill, Moody. It was a great question, and functional programming is one of my favorite aspects of R, so I love seeing questions in that area. – Artem Sokolov Sep 06 '18 at 22:28

0 Answers0