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

if और else

if और else R को choose करने देते हैं क्या करना है, 'अगर ठंड हो एक coat पहनो, नहीं तो एक t-shirt पहनो' की तरह। एक block का code सिर्फ तभी चलता है जब इसका question TRUE हो।

In this page:

  1. if / else
Syntax
r
if (condition) {
  # runs when TRUE
} else if (other_condition) {
  # runs when other_condition is TRUE
} else {
  # otherwise
}

if / else

एक if statement सिर्फ तभी एक block चलाता है जब इसकी condition TRUE हो; एक optional else नहीं तो चलता है। Condition एक single logical value evaluate होनी चाहिए, एक vector नहीं -- एक vector condition इस्तेमाल करना R version के हिसाब से एक error या warning trigger करता है।

जब कई lines में लिखा हो else को if block के closing brace के same line पर appear होना चाहिए।

Warning: if() में condition एक single TRUE/FALSE value होनी चाहिए, एक vector नहीं -- vectorized conditions के लिए ifelse() या all()/any() इस्तेमाल करें।

उदाहरण: if / else

markup
score <- 85

if (score >= 90) {
  cat("Grade: A\n")
} else if (score >= 70) {
  cat("Grade: B\n")
} else {
  cat("Grade: C\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. top level पर closing } के बाद एक नई line पर else रखना, जैसे } newline else {, जो braces के बाहर एक syntax error है।
  2. condition की तरह length 1 से बड़ा एक vector pass करना, जो recent R versions में एक error है; any() या all() या ifelse() इस्तेमाल करें।
  3. condition में == की बजाय = इस्तेमाल करना, जो compare करने की बजाय assign करता है।
🔒

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.