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

Scope क्या है

Scope इसके बारे में है कि एक नाम कहाँ देखा जा सकता है, एक room से belong करने वाले toys की तरह। एक function के अंदर बना एक variable इसके अंदर ही रहता है और बाहर leak नहीं होता।

In this page:

  1. Scope
Syntax
r
x <- global_value
function_name <- function() {
  x <- local_value    # local to the function
  x
}

Scope

एक function के अंदर बने variables उस function के execution के लिए local हैं और इसके return होते ही गायब हो जाते हैं, बाहर same नाम वाले variables को प्रभावित किए बिना।

R lexical scoping इस्तेमाल करता है, मतलब एक function अपने enclosing environment से variables पढ़ सकता है, लेकिन function के अंदर assignments default से outer वाले को modify करने की बजाय नए local variables बनाते हैं। <<- operator explicitly एक enclosing scope में एक variable modify कर सकता है, हालाँकि यह sparingly इस्तेमाल होता है।

Warning: एक function के अंदर <- से एक variable को assign करना एक नया local variable बनाता है -- यह function के बाहर same नाम वाला variable modify नहीं करता।

उदाहरण: Scope

markup
x <- "global value"

show_scope <- function() {
  x <- "local value"
  cat("Inside function:", x, "\n")
}

show_scope()
cat("Outside function:", x, "\n")
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 <- "local" global variable बदल देगा, जब यह एक local बनाता है।
  2. casually globals बदलने के लिए <<- इस्तेमाल करना, जो code follow करना मुश्किल बनाता है।
  3. return होने के बाद एक function के अंदर defined एक variable इस्तेमाल करना, जो object not found देता है।
🔒

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.