Add new Variables to a Data Frame using Existing Variables in R Programming – mutate() Function

mutate() function in R Language is used to add new variables in a data frame which are formed by performing operation on existing variables.

Syntax: mutate(x, expr)

Parameters:
x: Data Frame
expr: operation on variables

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to add new variables
# in a data frame
  
# Loading library 
library(dplyr)
    
# Create a data frame
d <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),  
                 age = c(7, 5, 9, 16),  
                 ht = c(46, NA, NA, 69), 
                 school = c("yes", "yes", "no", "no") ) 
    
# Calculating a variable x3 which is sum of height 
# and age printing with ht and age 
mutate(d, x3 = ht + age)  

chevron_right


Output:

     name age ht school x3
1    Abhi   7 46    yes 53
2 Bhavesh   5 NA    yes NA
3  Chaman   9 NA     no NA
4   Dimri  16 69     no 85

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to add new variables
# in a data frame
  
# Loading library 
library(dplyr)
    
# Create a data frame
d <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),  
                 age = c(7, 5, 9, 16),  
                 ht = c(46, NA, NA, 69), 
                 school = c("yes", "yes", "no", "no") ) 
    
# Calculating a variable x3 which is product of height 
# and age printing with ht and age 
mutate(d, x3 = ht * age)  

chevron_right


Output:

     name age ht school   x3
1    Abhi   7 46    yes  322
2 Bhavesh   5 NA    yes   NA
3  Chaman   9 NA     no   NA
4   Dimri  16 69     no 1104



My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.