📜  使用 R 编程中的现有变量将新变量添加到数据框中 – mutate()函数

📅  最后修改于: 2022-05-13 01:55:40.800000             🧑  作者: Mango

使用 R 编程中的现有变量将新变量添加到数据框中 – mutate()函数

R 语言中的mutate()函数用于在数据框中添加新变量,这些变量是通过对现有变量执行操作而形成的。

示例 1:

# 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)  

输出:

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

示例 2:

# 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)  

输出:

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