June 4, 2021

R Conditional Statements if else

Conditional Statements, if else, ifelse function, switch, in R

if block syntax:
if (test_expression) {
   statement
}

if-else block syntax:
if (test_expression) {

   statement1
} else {
   statement2
}

if-elseif-else block syntax:
if (test_expression1) {

   statement1
} else if (test_expression2) {
   statement2
} else if (test_expression3) {
   statement3
} else
   statement4

It's important that the else if keywords comes on the same line as the closing bracket of the previous part of the control construct.


y <- if(x > 2) 4 else 8


if(x > 0) print("Positive number") else print("Negative number")

if (total > 999)

{
  print("You are out of cash!")
} else if (total <800) {
  print("You can buy some Goodies!")
} else {
  print("Your shopping is done, but No Goodies!")
}

if(person$marital == "married")

{
  if(person$housing == "yes" | person$salary > 50000)
  {
    print("Issue credit card")
  } else
  {
    print("Sorry, you are not eligible for credit card")
  }
} else if(person$marital == "single")
{
  if(person$education == "tertiary" & person$salary > 30000)
  {
    print("Issue credit card")
  } else
  {
      print("Sorry, you are not eligible for credit card")
  }
}

if (test1 & test2 & test3){

    cat("Your answers are correct! Good job...\n")
}

if (!"cars_cyl" %in% l| !"cars_4" %in% l | !"cars_3" %in% l) {

  cat('You have not created all three variables. Please have a look!\n')
}

ifelse function in R:
ifelse(test_expression, x, y)
ifelse(vector_r %% 2 == 0, "even", "odd")
ifelse(num_char < med_num_char, "below median", "at or above median")
odi$century <- ifelse(odi$Runs > 99, 1, 0)
grades$penalized <- ifelse(grades$date >"2017-11-03", 1, 0)

switch function in R:
switch (statement, list)
switch(EXPR, ...)
> switch(2, "red", "green", "blue")
> x <- switch(4, "red", "green", "blue")
> switch("color", "color" = "red", "shape" = "square", "length" = 5)
cat(ch,":", switch(EXPR = ch, a = 1, b = 2:3), "\n")
switch(ff[1], A = "I am A", B="Bb..", C=" is C")
switch(2, invisible(pi), pi)

Related Articles: Distributions in R   R Format functions

No comments:

Post a Comment