Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Creating functions
If statements
13. if-else statements


Well done! In the last exercise, we executed some code only when a specified condition was met. What about when the condition is not met? We saw in the last instruction that nothing happens in that case. But what if we want to run some other code when a condition is not met? For that, you can use an if-else statement.

For example, if we're located in Amsterdam, we could view all other cities as being "foreign". So we may wish to assign a generic nationality of "Foreigner" to any city that isn't Amsterdam:

if (city == "Amsterdam") {
  nationality <- "Dutch"
} else {
  nationality <- "Foreigner"

Now if we're considering a city named Zagreb, its nationality will be defined because the code after the else keyword will be executed.


In the last exercise, we created and populated the response_missing variable only if the condition

if(sum($love_your_job)) > 0)
was met. If this condition is not met, then response_missing should be set to 0. Use an if-else statement to accomplish this.