Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Create new variables
2. Use if_else()
Grouping and statistical functions
Joining datasets
Summary

Instruction

Well done! Let's try another useful function, if_else(). As you might expect, it combines the statements IF and ELSE. The first argument is the logical condition (e.g., x < 10). The second argument is what should return if the condition is TRUE, and the third argument is what should return if the condition is FALSE.

Suppose we want to check our mood using the variable x. If x is greater than 20, we're happy; if not, we're sad. Here's how we'd code this:

if_else(x < 20, "Happy!", "Sad")

Exercise

Create a variable called age with a value of 18. Then use if_else() to check if a person is 'Adult' (18 or older) or a 'Child' (younger than 18).

Stuck? Here's a hint!

Type:

age <- 18
if_else(age >= 18, "Adult", "Child")