R语言 使用现有变量向数据框添加新的变量 – mutate() 函数

R语言 使用现有变量向数据框添加新的变量 – mutate() 函数

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

语法: mutate(x, expr)

参数:

x: 数据框

expr: 对变量的操作

例子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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程