Define an anonymous function without using the `function` keyword

  • A+
Category:Languages

I can define and use an anonymous function and call it like this

x <- 1:3 sapply(x, function(x) x) 

Sometimes I feel that using function like this is too verbose. Is there another way to define an anonymous function?

In the purrr package, one can define an anonymous function like this

map(x, ~.x) 

but this only works in the purrr context.

 


How less verbose could you make it? You need some kind of indicator that this is a function, some way of saying the arguments, and some way of saying the calculation. The only thing that makes it "verbose" is that "function" has eight letters. If you don't want that then define your function outside the apply and then you get sapply(x, foo) which is concise and descriptive and well-understood without resort to external dependencies (purrrr) or non-standard evaluation.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: