当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R语言 mutate()用法及代码示例


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

用法: 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



相关用法


注:本文由纯净天空筛选整理自nidhi_biet大神的英文原创作品 Add new Variables to a Data Frame using Existing Variables in R Programming – mutate() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。