Explain with an example how to implement if,else and elseif statement in R.

1.0K    Asked by Aalapprabhakaran in Data Science , Asked on Nov 21, 2019

If,else and elseif is used to apply logic to our code based on certain conditions.

The basic syntax of if,else statement is

if (condition) {

  # Code to execute if true

} else {

  # Code to execute if above was not true

}

Let us explain with an example

# Items sold that day

ham <- 10

cheese <- 10

# Report to HQ

report <- 'blank'


if(ham >= 10 & cheese >= 10){

    report <- "Strong sales of both items"

}else if(ham == 0 & cheese == 0){

    report <- "Nothing sold!"

}else{

    report <- 'We had some sales'

}

print(report)

Output:

[1] "Strong sales of both items"



Your Answer

Interviews

Parent Categories