← Back to R Course | Chapter 11: Apply Family | Lesson 6 of 6

Reduce() का उपयोग

Reduce एक list को step by step काम करके एक value में combine करता है, एक jar में coins एक-एक करके add करने की तरह जब तक आपके पास एक total न हो। हर step अब तक का running result इस्तेमाल करता है।

In this page:

  1. Reduce()
Syntax
r
Reduce(FUN, x)
Reduce(FUN, x, accumulate = TRUE)

Reduce()

Reduce(FUN, x) एक binary function बार-बार apply करके एक vector के सारे elements को एक single value में combine करता है, + से एक list fold करके एक sum पाने की तरह।

Reduce("+", c(1,2,3,4)) ((1+2)+3)+4 compute करता है। accumulate = TRUE pass करना सिर्फ final result की बजाय हर intermediate result return करता है।

Note: Reduce("+", x) sum(x) का एक functional-programming alternative है, useful जब combining function एक simple built-in न हो।

उदाहरण: Reduce()

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

total <- Reduce("+", numbers)
cat("Total:", total, "\n")

running <- Reduce("+", numbers, accumulate = TRUE)
print(running)
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. एक init value के बिना एक empty vector पर Reduce इस्तेमाल करना, जो NULL return करता है।
  2. बिना quotes के Reduce(+, numbers) लिखना, जो एक syntax error है; "+" या ` + ` इस्तेमाल करें।
  3. जब आपको running results चाहिए accumulate = TRUE भूल जाना।
चैप्टर सारांश
  • Apply family बिना explicit loops लिखे data के आर-पार एक function apply करती है।
  • apply(), lapply(), sapply(), और tapply() matrices, lists, और groups पर काम करते हैं।
  • Map() और Reduce() functions से data combine या transform करते हैं।
🔒

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.