How to use mutate() method In R Language
The data transformation in R mutate() method is used to create and modify new variables in the specified data frame. A new column name can be assigned to the data frame and evaluated to an expression where constants or column values can be used. The output data frame has the new columns created. The method has the following syntax :
Syntax: mutate (new-col-name = expr)
Parameters:
- new-col-name – Name of column to be created.
- expr – Expression which is applied on new column.
Multiple columns can also be added to the data frame and separated using the comma operator. The following code snippet illustrates the addition of two new columns, col5, which is the summation of col1 and col4 values, and col6, which is constant 1 added to the col3 values. For example, in first row col1 = 2 and col4 = 9 , therefore col5 = 2 + 9 = 11. And col6 is the addition of col3 value and 1.
R
# Importing tidyverse library (tidyverse) # Creating a data frame data_frame = data.frame ( col1 = c (2,4,1,7,5,3,5,8), col2 = letters [1:8], col3 = c (0,1,1,1,0,0,0,0), col4 = c (9:16)) print ( "Data Frame" ) print (data_frame) # Added new columns data_frame_mutate <- data_frame %>% mutate (col5 = col1 + col4 , col6 = col3+1) print ( "Mutated Data Frame" ) print (data_frame_mutate) |
Output:
col1 col2 col3 col4
1 2 a 0 9
2 4 b 1 10
3 1 c 1 11
4 7 d 1 12
5 5 e 0 13
6 3 f 0 14
7 5 g 0 15
8 8 h 0 16
[1] "Mutated Data Frame"
col1 col2 col3 col4 col5 col6
1 2 a 0 9 11 1
2 4 b 1 10 14 2
3 1 c 1 11 12 2
4 7 d 1 12 19 2
5 5 e 0 13 18 1
6 3 f 0 14 17 1
7 5 g 0 15 20 1
8 8 h 0 16 24 1
How to Transform Data in R?
In this article, we will learn how to transform data in the R programming language.
Contact Us