Using mutate to change or create a column
Suppose we want life expectancy to be measured in months instead of years: you'd have to multiply the existing value by 12. You can use the mutate()
verb to change this column, or to create a new column that's calculated this way.
This is a part of the course
“Introduction to the Tidyverse”
Exercise instructions
- Use
mutate()
to change the existinglifeExp
column, by multiplying it by 12:12 * lifeExp
. - Use
mutate()
to add a new column, calledlifeExpMonths
, calculated as12 * lifeExp
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
library(gapminder)
library(dplyr)
# Use mutate to change lifeExp to be in months
# Use mutate to create a new column called lifeExpMonths
This exercise is part of the course
Introduction to the Tidyverse
Get started on the path to exploring and visualizing your own data with the tidyverse, a powerful and popular collection of data science tools within R.
In this chapter, you'll learn to do three things with a table: filter for particular observations, arrange the observations in a desired order, and mutate to add or change a column. You'll see how each of these steps allows you to answer questions about your data.
Exercise 1: The gapminder datasetExercise 2: Loading the gapminder and dplyr packagesExercise 3: Understanding a data frameExercise 4: The filter verbExercise 5: Filtering for one yearExercise 6: Filtering for one country and one yearExercise 7: The arrange verbExercise 8: Arranging observations by life expectancyExercise 9: Filtering and arrangingExercise 10: The mutate verbExercise 11: Using mutate to change or create a columnExercise 12: Combining filter, mutate, and arrangeWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.