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:
()
as usual, to denote a call to a function, immediately after the keyword function
: this can specify the argument, in example x
;()
couple encircles the function(x)
declaration and body;# 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
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
Through the standard form offers different advantages in mathematical calculations and scientific notation. Firstly, it…
Introduction Stress is a feeling caused by an external trigger that makes us frustrated, such…
Sociology is a broad discipline that examines societal issues. It looks at the meaningful patterns…
Some info about Inch Inches are a unique measure that persuades us that even the…
You should be familiar with logarithms to understand antilogarithms in a better manner. Logarithms involve…
यहां "नाटककार सुरेंद्र वर्मा" पुस्तक की पीडीएफ विद्यार्थी, शोधार्थी और जो इसका अभ्यास के लिए…