Function (x) in R: writing a “function” without defining a function?

I came across this concept a couple of times, but don’t know what her name is, so he cannot google to find out more. Basically, when looking at functions or even simple commands written by others, I often see something similar to this:

apply(dataset, 1:2, function(x) 10 * x) 

In this case, I managed to find out that somehow this "fake function" (x) function simply multiplies each element of the data set by 10. This seems like a useful function, but I'm still not sure when and how you use it. Is this really a feature? Or does it just work within the framework of the applied family of functions? Is there a name for this thing?

+5
source share
2 answers

Those are called "anonymous functions", and yes, they are objects of real functions that simply are not assigned to any character before use.

Here is the corresponding bit from the documentation in the R language :

Functions are usually assigned to characters, but they should not be. The value returned by the function call is a function. If this name is not specified, it is called an anonymous function. Anonymous functions are most often used as arguments to other functions, such as an application family or an external one.

Although they are most often used in *apply() functions, they do not have to be, as you can see here, for example

 (function(x,y){x*y + x/y})(2,5) # [1] 10.4 
+8
source

Do you mean lambda (anonymous function)? You can add something like this to your ~/.Rprofile file:

 `{` <- function(...) base::`{`( if (length(sys.calls()) >= 4 && identical(as.character(sys.call()[[1]]), "{") && identical(as.character(sys.call(-4)[[1]]), "{")) base::`{`(fn <- new('function'), formals(fn) <- alist(x=), body(fn) <- sys.call(), fn) else eval.parent(substitute(base::`{`(...))) ) 

Then you can do things like:

 sapply(1:10, {{x + 5}}) # [1] 6 7 8 9 10 11 12 13 14 15 

This is closer to languages ​​like Ruby or Coffeescript that don't need to refer to a keyword to create a lambda (they use -> , but this is already done in R, so I used double curly braces). I just came up with this, so if there are any errors let me know.

+6
source

Source: https://habr.com/ru/post/1205641/


All Articles