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

sapply() का उपयोग

sapply lapply जैसा काम करता है लेकिन possible होने पर answers को एक simple vector में tidy करता है, results को एक neat row में collect करने की तरह। यह simple cases के लिए एक friendlier version है।

In this page:

  1. sapply()
Syntax
r
result <- sapply(x, FUN)

sapply()

sapply(x, FUN) lapply() जैसा काम करता है लेकिन हमेशा एक list return करने की बजाय possible होने पर result को एक vector या matrix में simplify करने की कोशिश करता है।

यह इसे common case के लिए lapply() से ज़्यादा convenient बनाता है जहाँ हर call एक single value produce करती है। अगर simplification possible न हो, sapply() lapply() की तरह ही एक list return करने पर fall back करता है।

Note: sapply() essentially "lapply() plus automatic simplification" है -- पहले इसके लिए reach करें, और specifically जब आपको एक list चाहिए lapply() इस्तेमाल करें।

उदाहरण: sapply()

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

squared <- sapply(numbers, function(x) x^2)
print(squared)
cat(class(squared), "\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. यह उम्मीद करना कि sapply हर बार एक vector return करेगा, जब results की lengths अलग हों तो यह एक list return कर सकता है।
  2. एक empty input पर sapply इस्तेमाल करना, जो एक vector की बजाय list() return करता है।
  3. जहाँ type जानना ज़रूरी हो वहाँ sapply इस्तेमाल करना, जब vapply इसे check करता है।
🔒

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.