mutate & transmute R Functions of dplyr Package (2 Example Codes)
The post is structured as follows:
- Creating Example Data
- Example 1: Application of mutate Function
- Example 2: Application of transmute Function
- Video & Further Resources
Let’s take a look at some R codes in action.
Creating Example Data
Before we can start with the application of mutate and transmute, we need to create some example data in R:
data <- data.frame(x1 = 1:5, # Create example data x2 = 5:9) data # Print example data # x1 x2 # 1 1 5 # 2 2 6 # 3 3 7 # 4 4 8 # 5 5 9
We also need to install and load the dplyr package of the tidyverse environment:
install.packages("dplyr") # Install dplyr add-on package library("dplyr") # Load dplyr add-on package
Now, we can move on to the programming examples…
Example 1: Application of mutate Function
Example 1 shows how to use the mutate function in R. Let’s assume that we want to create a new column containing the sum of our two original columns x1 and x2. Then we can use the mutate function as follows:
mutate(data, x3 = x1 + x2) # Apply mutate function # x1 x2 x3 # 1 1 5 6 # 2 2 6 8 # 3 3 7 10 # 4 4 8 12 # 5 5 9 14
As you can see based on the previous output of the RStudio console, the mutate function created a new data frame consisting of our original data plus a new variable containing the sum of our original data.
Example 2: Application of transmute Function
The second example explains how to apply the transmute function and its difference compared to the mutate function. Let’s have a look at the transmute command in action:
transmute(data, x3 = x1 + x2) # Apply transmute function # x3 # 1 6 # 2 8 # 3 10 # 4 12 # 5 14
The transmute function returns the same new variable as mutate. However, it does not retain our original data!
Video & Further Resources
Have a look at the following video that I have published on my YouTube channel. I’m explaining the content of this article in the video.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you could have a look at the related tutorials on this website. I have released numerous posts about the dplyr package already:
- Numbering Rows within Groups
- The dplyr Package
- R Functions List (+ Examples)
- The R Programming Language
Summary: You learned in this article how to create or transform variables of data frames and tibbles with dplyr in the R programming language. If you have additional comments and/or questions, let me know in the comments.
Statistics Globe Newsletter