← Back to R Course | Chapter 4: Control Flow | Lesson 2 of 6

ifelse() का उपयोग

ifelse एक list में हर item के बारे में same yes-or-no question पूछता है और हर एक के लिए दो answers में से एक चुनता है। यह एक teacher की तरह है जो एक बार में पूरी class को pass या fail mark करता है।

In this page:

  1. ifelse()
Syntax
r
result <- ifelse(condition, value_if_true, value_if_false)

ifelse()

ifelse(condition, yes, no) if/else का एक vectorized version है, पूरे vector में element-wise एक condition evaluate करते हुए और results का एक vector return करते हुए।

यह हर element पर conditional logic apply करने के लिए एक loop लिखने से बचाता है। यह condition के आधार पर data transform करने के लिए R के सबसे common idioms में से एक है।

Note: जब आपको पूरे vector पर एक साथ एक condition apply करनी हो, सिर्फ एक single value पर नहीं, ifelse() इस्तेमाल करें।

उदाहरण: ifelse()

markup
scores <- c(95, 60, 78, 40, 88)

results <- ifelse(scores >= 70, "Pass", "Fail")
print(results)
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. जब element-wise results के लिए ifelse() चाहिए पूरे vector पर if इस्तेमाल करना।
  2. यह उम्मीद करना कि ifelse() दोनों branches के types रखेगा, जब result test और chosen values के आधार पर एक type लेता है।
  3. यह भूल जाना कि test में एक NA result में NA देता है।
🔒

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.