Mutate Existing Variables
Learn how to create new data based on existing columns.
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:
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 ...