Multiple Transformations

We wish to carry out multiple data transformation operations on the same data frame.

df_2 = df %>%
  mutate(
    col_4 = !col_3,
    col_5 = abs(col_2),
    col_6 = round(col_1, 2),
    col_7 = col_5 / col_6
  )

Here is how this works:

  • We can create or modify multiple columns in a single call to mutate(). To do so, we pass to mutate() multiple data transformation expressions, such as those covered in Common Transformation Scenarios, separated by commas.
  • In this example, the data transformation expressions are:
    • col_4 = !col_3 where we use the logical complement operator ! to create a new column col_4 that is the logical complement of column col_3 which is of a logical data type, i.e. it can take the values TRUE or FALSE.
    • col_5 = abs(col_2) where we create a new column col_5 whose values are the absolute values of the corresponding values of the numeric column col_1.
    • col_6 = round(col_1, 2) where we create a new column col_6 whose values are the rounding to 2 decimal places of the corresponding values of the numeric column col_2.
    • col_7 = col_5 / col_6 where we create a new column col_7 whose values are the ratio of the two columns col_5 and col_6.
  • We can use columns created earlier in the same mutate() statement as inputs to data transformation expressions which we do here in col_7 = col_5 / col_6.
  • The resulting columns will be added on the right end of the original data frame and in the same order they are defined in the mutate() function. If an existing column is overwritten, it’s position is not changed.
R
I/O