case_when()

If you are conditionally changing more than one value (or even just one), case_when() is a very useful function. With case_when() you can put a list of conditional statements that will be evaluated one-by-one, in order, to help you change values. The syntax is nicer than using multiple | (OR) statements with if_else().

case_when()

Let’s use case_when() on our traffic light example and we’ll add the option “caution” for “yellow”. Here’s the data:

The syntax for case_when() is to put your conditional statement, then ~, then the value if the statement is TRUE. You can stack up as many of these as you want. For your values that evaluate FALSE for every statement, you can add .default onto the end to keep them as is or leave that argument off to have them replaced with NA.

Try using case_when() with the {palmerpenguins} data. Let’s add a column to penguins called size which will label penguins as “large” or “small” based on whether they weigh more or less than 4000g. First let’s shrink the dataset so you’ll be able to see if your column appears.

Now add your code for creating the size column. Note from running summary() that there are two NA values, let’s change them to say “missing”.

Multiple Conditions

Let’s say we want to add a column called valid to a dataset to see if we should include someone in our experiment. Here’s the current data that records a student’s age and whether they have signed a waiver.

Let’s say that students can participate if they are over 18 and if they have signed a waiver. We can use both of these conditional statements in the same case_when(), you don’t only need to be evaluating on a single variable. Here’s our statement with conditionals from two different variables:

This is essentially the same as using an | (OR) operator. We can still use our logical operators within case_when(). Let’s use the logical operator & (AND) to mark valid as “yes” only if someone is over 18 and they have a signed waver. We do this similarly to how we did with if_else(), but add both conditions before the ~: