← Back to R Course | Chapter 12: Best Practices | Lesson 2 of 6

Loops की जगह Vectorization

Vectorization का मतलब है एक पूरी list पर एक action एक साथ करना बजाय एक loop में item by item के। यह पानी को एक spoon से move करने की बजाय एक पूरी bucket उड़ेलने जैसा है, और R में यह तेज़ है।
Syntax
r
result <- vector_name * 2        # vectorized
result <- function_name(vector_name)

Loops की बजाय Vectorization

R vectorized operations के लिए optimized है -- एक पूरे vector पर एक साथ एक function apply करना -- जो एक equivalent element-by-element for loop से कहीं तेज़ चलते हैं, क्योंकि vectorized operations under the hood optimized C code में implement हैं।

Manually loop करने और एक result vector में append करने से v * 2, sum(v), या sapply() prefer करें। यह R में सबसे important performance habits में से एक है।

Warning: result <- c(result, new_value) से एक loop के अंदर एक vector grow करना एक classic R performance trap है -- यह हर iteration पर memory reallocate करता है।

उदाहरण: Vectorization over Loops

markup
numbers <- 1:1000000

# Vectorized (fast, idiomatic)
squared_vectorized <- numbers^2

# A loop would work but be far slower for this size of data
cat("First 5 squared values:", head(squared_vectorized, 5), "\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. result <- c(result, x^2) से एक loop में एक vector grow करना, जो slow हो जाता है क्योंकि यह हर बार copy करता है।
  2. sum या numbers^2 जैसी चीज़ के लिए एक loop लिखना, जब एक vectorised form छोटा और तेज़ है।
  3. एक vectorised approach के अंदर vectors पर if इस्तेमाल करना, जब ifelse() चाहिए।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 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.