R Language: if-else

0

The if-else statement is a control structure that allows you to test a condition and act on it depending on whether it's true or false. The syntax for an if-else statement is as follows:

if (condition) {

  # do something if condition is true

} else {

  # do something if condition is false

}

For example, the following code will print "The number is greater than 5" if the variable `x` is greater than 5, and "The number is less than or equal to 5" if it's not:

x <- 10


if (x > 5) {

  print("The number is greater than 5")

} else {

  print("The number is less than or equal to 5")

}

The else clause is optional. If you don't include it, the code will simply skip to the next line if the condition is false.

You can also have multiple if-else statements, with each one testing a different condition. For example, the following code will print "The number is positive" if `x` is greater than 0, "The number is zero" if `x` is equal to 0, and "The number is negative" if `x` is less than 0:

x <- -5


if (x > 0) {

  print("The number is positive")

} else if (x == 0) {

  print("The number is zero")

} else {

  print("The number is negative")

}

Post a Comment

0Comments
Post a Comment (0)