Anonymous Functions क्या हैं
एक anonymous function बिना नाम का एक छोटा helper है, एक quick note की तरह जो आप एक friend को पास करते हैं और फिर फेंक देते हैं। यह handy है जब किसी दूसरे function को एक छोटी instruction चाहिए।
In this page:
Syntax
function(x) expression
(function(x) expression)(value)
sapply(vector_name, function(x) expression)
Anonymous Functions
R आपको बिना नाम दिए एक function define करने देता है, useful जब एक छोटा function सीधे किसी दूसरे function को, जैसे sapply(), एक argument की तरह pass करना हो।
R 4.1 से, compact \(x) x * 2 syntax function(x) x * 2 के लिए एक shorthand है। Anonymous functions short, one-off logic inline रखते हैं एक separate named definition की ज़रूरत की बजाय।
Note:
backslash shorthand \(x) ... (R 4.1+) छोटे anonymous functions के लिए function(x) ... लिखने का एक ज़्यादा concise alternative है।
उदाहरण: Anonymous Functions
numbers <- c(1, 2, 3, 4)
squared <- sapply(numbers, function(x) x * x)
print(squared)
doubled <- sapply(numbers, \(x) x * 2)
print(doubled)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
function(x) x * xकिसी चीज़ को pass किए बिना लिखना, और इसके खुद चलने की उम्मीद करना।- 4.1 से पहले R versions पर
\(x)shorthand इस्तेमाल करना, जहाँ यह एक syntax error है। - यह भूल जाना कि
sapplyएक vector return करता है लेकिन एक list return कर सकता है जब results length में अलग हों।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: