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

Instruction

Perfect! You're now ready to start writing more complex functions.

Sometimes, we want to execute a certain instruction only if a condition is met. To that end, we use if statements:

if (city == "Amsterdam") {
  nationality = "Dutch"
}

It starts with the if keyword. Within the parentheses, you specify a logical condition that has to be met in order for the code in the braces to be executed. In our example, we'll set the nationality to Dutch only if the city is Amsterdam.

For any other city (e.g., Zagreb), the nationality variable will not be defined because the condition will not have been met.

Exercise

Both love_your_job and searching_job are columns that store participants' answers to job satisfaction questions from the survey. Usually, we shouldn't have NAs in columns that represent answers. Write an if statement that stores a value of 1 in a new variable named response_missing if there are NAs in the love_your_job column.

Stuck? Here's a hint!

Type:

if (any(is.na(survey$love_your_job)) > 0) {
  response_missing <- 1
}