Get startedGet started for free

The mutate() verb

1. The mutate() verb

Datasets don't always have the variables we need. We can use the mutate() verb to add new variables or change existing variables.

2. Selecting columns

Let's start with a dataset where we've selected four interesting variables: state, county, population, and unemployment. The unemployment rate is given as a percentage, so 5 would mean 5 percent, or one twentieth.

3. Total number of unemployed people

What if we were interested in the total number of unemployed people in a county, rather than as a percentage of the population? We could use the formula population times unemployment divided by 100.

4. mutate()

We use the mutate() verb to calculate this variable and add it to the dataset as a new variable, which we'll name unemployed-underscore-population. We pipe from counties_selected, then call mutate on our unemployed population formula. Notice that the new dataset has the variable unemployed_population added to it. We got to choose the name of this variable by putting unemployed-underscore-population before the equals sign.

5. mutate() and arrange()

We can combine this new variable with other verbs to answer more questions with our dataset. For example, which counties have the highest number of unemployed people? We'd add arrange desc unemployed-underscore-population after the mutate.

6. Selecting and transforming with mutate()

mutate() can also be used to select and transform columns in one go! Let's return to the counties dataset and instead of using a select first to select the columns of interest, list them inside mutate, along with the unemployed_population column to create. Specifying dot-keep equals "none" means that any column not included in mutate() is discarded. We'll again finish by sorting by unemployed_population in descending order. We got the same result as before, but with one fewer function used.

7. Let's practice!

In the exercises, you'll add a few new variables and answer questions based on them with the filter and arrange verbs.

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.