Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function(x) in R: writing a "function" without defining a function?

Tags:

function

r

I have come across this concept a couple of times, but don't know the name for it so cannot google it to learn more. Basically, when looking through functions or even simple commands others have written I will often see something similar to this:

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

In this case, I was able to figure out that somehow this "fake function" function(x) would just multiply each element of the dataset by 10. This seems like a useful feature, but I'm still not certain when or how you use it. Is it really a function? Or does it just work within the apply family of functions? Is there a name for this thing?

like image 526
HFBrowning Avatar asked Oct 27 '14 20:10

HFBrowning


1 Answers

As of R 4.1.0, it is now possible to natively use \(x) {} instead of function(x) {} for anonymous function.

The apply code can be written as

dataset |>
    apply(1:2, \(x) {10 * x})
like image 92
YCR Avatar answered Oct 14 '22 03:10

YCR