Loops की जगह Vectorization
Vectorization का मतलब है एक पूरी list पर एक action एक साथ करना बजाय एक loop में item by item के। यह पानी को एक spoon से move करने की बजाय एक पूरी bucket उड़ेलने जैसा है, और R में यह तेज़ है।
In this page:
Syntax
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
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")
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. #}
आम गलतियां
result <- c(result, x^2)से एक loop में एक vector grow करना, जो slow हो जाता है क्योंकि यह हर बार copy करता है।sumयाnumbers^2जैसी चीज़ के लिए एक loop लिखना, जब एक vectorised form छोटा और तेज़ है।- एक vectorised approach के अंदर vectors पर
ifइस्तेमाल करना, जबifelse()चाहिए।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: