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
相關用法
- R語言 data.matrix()用法及代碼示例
- R語言 with()用法及代碼示例
- R語言 expand.grid()用法及代碼示例
- R語言 subset()用法及代碼示例
- R語言 melt()用法及代碼示例
- R語言 rename()用法及代碼示例
- R語言 select()用法及代碼示例
- R語言 summarise()用法及代碼示例
- R語言 sample_n()用法及代碼示例
- R語言 transform()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi_biet大神的英文原創作品 Add new Variables to a Data Frame using Existing Variables in R Programming – mutate() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。