Press "Enter" to skip to content

Anonymous Functions in R

Zigya Acadmey 0

In R, functions are objects in their own right. They aren’t automatically bound to a name. Unlike many languages (e.g., C, C++, Python, and Ruby), R doesn’t have a special syntax for creating a named function: when you create a function, you use the regular assignment operator to give it a name. If you choose not to give the function a name, you get an anonymous function.

When you don’t give a name to a function, you are creating an anonymous function.

You use an anonymous function when it’s not worth the effort to give it a name:

The syntax is slightly different from the ordinary UDF seen above because now you have a different parentheses approach:

  • First, you use () as usual, to denote a call to a function, immediately after the keyword function: this can specify the argument, in example x;
  • Secondly, a () couple encircles the function(x) declaration and body;
  • Thirdly, after the previous construct, you specify the argument passed in the call.

Example:

# Anonymous function for cude
> (function(x) x * x * x)(9)
[1] 729

# Same as
> fun <- function(x) x * x * x

# Call `fun` and pass `9` as an argument
> fun(9)
[1] 729

R Convention

The most common convention is to use anonymous functions when using the *apply family of functions. For example, you might want to do an operation across a set of columns in a dataset.

# Create a dataset
df <- data.frame(
  col1 = c("e1", "e2"),
  col2 = c("e3", "e4"),
  stringsAsFactors = FALSE
)

# lapply an anonymous function to the columns of the dataset
> lapply(df, function(x) paste(x, "is working"))
$col1
[1] "e1 is working" "e2 is working"

$col2
[1] "e3 is working" "e4 is working"

Conclusion

Hence, we saw what is a anonymous function, when to use a anonymous function with a example.

This brings the end of this Blog. We really appreciate your time.

Hope you liked it.

Do visit our page www.zigya.com/blog for more informative blogs on Data Science

Keep Reading! Cheers!

Zigya Academy
BEING RELEVANT

Leave a Reply

Your email address will not be published. Required fields are marked *