Search⌘ K

Mutate Existing Variables

Explore how to use the mutate() function in R's dplyr package to create and modify variables based on existing data. Understand practical examples such as temperature conversion and flight delay calculations. Learn to manage data frames by overwriting or adding variables thoughtfully and organize data using arrange and desc functions to enhance your data wrangling skills.

Example with the temperature dataset

Another common transformation of data is to create/compute new variables based on existing ones. For example, lets say we’re more comfortable thinking of temperature in degrees Celsius (°C) instead of degrees Fahrenheit (°F). The formula to convert temperatures from °F to °C is:

We can apply this formula to the temp variable using the mutate() function from the dplyr package, which takes existing variables and mutates them to create new ones.

Example with the weather dataset

For example, let’s consider the weather data frame to apply the mutate() function:

R
weather <- weather %>%
mutate(temp_in_C = (temp - 32) / 1.8)

In this code, we mutate() the weather data frame by creating a new variable temp_in_C = (temp - 32) / 1.8) and then overwrite the original weather data frame. Why did we overwrite the weather data frame instead of assigning the result to a ...