← Back to R Course | Chapter 5: Functions | Lesson 6 of 7

Anonymous Functions क्या हैं

एक anonymous function बिना नाम का एक छोटा helper है, एक quick note की तरह जो आप एक friend को पास करते हैं और फिर फेंक देते हैं। यह handy है जब किसी दूसरे function को एक छोटी instruction चाहिए।

In this page:

  1. Anonymous Functions
Syntax
r
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

markup
numbers <- c(1, 2, 3, 4)

squared <- sapply(numbers, function(x) x * x)
print(squared)

doubled <- sapply(numbers, \(x) x * 2)
print(doubled)
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. #}
आम गलतियां
  1. function(x) x * x किसी चीज़ को pass किए बिना लिखना, और इसके खुद चलने की उम्मीद करना।
  2. 4.1 से पहले R versions पर \(x) shorthand इस्तेमाल करना, जहाँ यह एक syntax error है।
  3. यह भूल जाना कि sapply एक vector return करता है लेकिन एक list return कर सकता है जब results length में अलग हों।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.