The Power of mutate( ) for Data Wrangling in R | by Gustavo Santos | Towards Data Science

Most of the data wrangling and transformations related posts I see around are using Pandas. I, myself, being a Pandas lover, wrote a few of those already. But it is good to know that there are other great tools that will help you to make the same transformations. Sometimes that’s easier, sometimes not that much.
When I learned R Language a couple of years ago, I had to import many libraries for data wrangling, like dplyr , tidyr etc. Now, after tidyverse package came up, you just add that line library(tydiverse) and you will be good to go with all of those transformations shown in this post.
Reminder: to install libraries in R it’s just install.packages("lib name") .
Let’s get coding. And to kick us off I’ll create this simple dataset to serve as our example.
# creating a dataframedf <- data.frame(col1=c(1,2,3,4,5,7,6,8,9,7),                 col2=c(2,3,4,5,6,5,5,4,6,3),                 col3=c(5,7,8,9,9,3,5,3,8,9),                 col4=c(43,54,6,3,8,5,6,4,4,3))     col1 col2 col3 col41     1    2    5   43     2     2    3    7   54      3     3    4    8    6      4     4    5    9    3      5     5    6    9    8      6     7    5    3    5      7     6    5    5    6      8     8    4    3    4       9     9    6    8    4      10    7    3    9    3     
mutate() is a dplyr function that adds new variables and preserves existing ones. That’s what the documentation says. So when you want to add new variables or change one already in the dataset, that’s your good ally.
Given our dataset df , we can easily add columns with calculations.
# Add mean, std and median of columnsmutate(df, mean_col1 = mean(col1),       std_col2 = sd(col2),        median_col3 = median(col3))     col1 col2 col3 col4 mean_col1 std_col2 median_col31     1    2    5   43       5.2 1.337494         7.52     2    3    7   54       5.2 1.337494         7.53     3    4    8    6       5.2 1.337494         7.54     4    5    9    3       5.2 1.337494         7.55     5    6    9    8       5.2 1.337494         7.56     7    5    3    5       5.2 1.337494         7.57     6    5    5    6       5.2 1.337494         7.58     8    4    3    4       5.2 1.337494         7.59     9    6    8    4       5.2 1.337494         7.510    7    3    9    3       5.2 1.337494         7.5
Add a new variable.
# Create new Variablenew_var <- c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')# Add it to the datasetmutate(df, new_var)
Replace a variable with changed data.
# Change column 1 to proportionsmutate(df, col1=proportions(col1)           col2 = col2*100)      col1     col2 col3 col41  0.01923077  200    5   432  0.03846154  300    7   543  0.05769231  400    8    64  0.07692308  500    9    35  0.09615385  600    9    86  0.13461538  500    3    57  0.11538462  500    5    68  0.15384615  400    3    49  0.17307692  600    8    410 0.13461538  300    9    3
Mutate can be combined with other great functions. Let’s go over a few examples.
recode() is a method to change the observations within a variable. It can be used together with mutate() .
# Change letters from 'new_var' to numbersmutate(df, new_var = recode(new_var,       'a' = 1, 'b' = 2, 'c' = 3, 'd' = 4, 'e' = 5,       'f' = 6, 'g' = 7, 'h' = 8, 'i' = 9, 'j' = 10)       )      col1 col2 col3 col4 new_var1     1    2    5   43       12     2    3    7   54       23     3    4    8    6       34     4    5    9    3       45     5    6    9    8       56     7    5    3    5       67     6    5    5    6       78     8    4    3    4       89     9    6    8    4       910    7    3    9    3      10
replace() is similar to recode, however it’s a package from base R and you can use it to change observations based on a list of values or one by one.
The replace function receives the variable column, a list of indexes to be changed and the list of values. Another option is to point a certain value you want to change and the replacement value.
# replace using index listmutate(df,       new_var = replace(new_var, c(1,2,3,4,5,6,7,8,9,10), c(1,2,3,4,5,6,7,8,9,10))       )# replace using value to be changedmutate(df,       new_var = replace(new_var, new_var=='a', 1)
cut() is a function from base R to transform observations in ranges of values, putting the values inside bins.
In the example below, I use cut to create two bins for column 1 [from minimum value to the mean and from the mean to the max value]. Then every value in the first bin will receive the label “lower than avg” while the second bin gets “above the avg”.
# Labeling with cutmutate(df, col1_label_avg = cut(col1,                             c(-Inf, mean(col1), max(col1)),                            c('lower than avg', 'above the avg')                                 )       )      col1 col2 col3 col4    col1_label_avg1     1    2    5   43      lower than avg2     2    3    7   54      lower than avg3     3    4    8    6      lower than avg4     4    5    9    3      lower than avg5     5    6    9    8      lower than avg6     7    5    3    5      above the avg7     6    5    5    6      above the avg8     8    4    3    4      above the avg9     9    6    8    4      above the avg10    7    3    9    3      above the avg
transmute() is another function from dplyr package. It adds new variables while it drops others. We could use it to add the col1 labels and drop the others unnecessary columns for the exercise.
mutate(df, col1_label_avg = cut(col1,                        c(-Inf, mean(col1), max(col1)),                       c('lower than avg', 'above the avg'))) %>%   transmute(col1, col1_label_avg) #drops other cols     col1   col1_label_avg1     1     lower than avg2     2     lower than avg3     3     lower than avg4     4     lower than avg5     5     lower than avg6     7     above the avg7     6     above the avg8     8     above the avg9     9     above the avg10    7     above the avg
select() is a function from dplyr and works a lot like the SQL statement. It selects the columns you want and puts them in the same order they were listed.
# Performing a transformation and selecting columnsdf %>%   mutate( col1_pct = proportions(col1) ) %>%   select (col1, col1_pct)
We can create some transformations and use select to order the columns the way we want.
df %>%   # add new column and calc proportion of col1  mutate( new_var, col1_pct = proportions(col1) ) %>%   # change values in new_var from letters to numbers, add as new col  mutate( new_var_numbers = replace(new_var,  1:10, 1:10) ) %>%  # select the transformed columns in the desired order  select (col1_pct, col1, new_var_numbers, new_var,)    col1_pct    col1    new_var_numbers   new_var1  0.01923077    1               1         a2  0.03846154    2               2         b3  0.05769231    3               3         c4  0.07692308    4               4         d5  0.09615385    5               5         e6  0.13461538    7               6         f7  0.11538462    6               7         g8  0.15384615    8               8         h9  0.17307692    9               9         i10 0.13461538    7              10         j
There’s so much you can do with mutate() . It is a powerful method from R Language and when combined with other methods, it boosts its possibilities.
Take advantage of it by practicing and applying to your data exploration. Use it with some of the other functions presented in this post.
mutate() : add or change variables. Apply calculations on variables.
recode() : change observations within variables.
replace() : similar to recode, but you can change values using lists.
cut() : put observations in ranges of values.
transmute() : adds new variables and discard others not listed.
select() : used to select or reposition variables.
If this content is interesting to you, don’t forget to follow me for more.