當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。