【807】R语言mutate与transmute函数
参考:R dplyr 函数介绍之 mutate(), transmute()
- %>%是tidyverse包里面用来进行管道化操作的函数。
- mutate()用来增加新的列,新增列通常在原数据框的最后面。
- transmute()函数用来仅仅保存新增的列。
mutate()R语言中的函数用于在 DataFrame 中添加新变量,这些变量是通过对现有变量进行操作而形成的。
用法: mutate(x, expr)
参数:
x:数据帧
expr:对变量的操作
举例:通过操作列进行创建新的列!
> d <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),
+ age = c(7, 5, 9, 16),
+ ht = c(46, 23, 34, 69),
+ school = c("yes", "yes", "no", "no") )
> d
name age ht school
1 Abhi 7 46 yes
2 Bhavesh 5 23 yes
3 Chaman 9 34 no
4 Dimri 16 69 no
> mutate(
+ d,
+ x3 = ht + age,
+ x4 = ht * age,
+ x5 = x3 + x4
+ )
name age ht school x3 x4 x5
1 Abhi 7 46 yes 53 322 375
2 Bhavesh 5 23 yes 28 115 143
3 Chaman 9 34 no 43 306 349
4 Dimri 16 69 no 85 1104 1189
transmute 举例:
> library(gcookbook)
> drunk
sex 0-29 30-39 40-49 50-59 60+
1 male 185 207 260 180 71
2 female 4 13 10 7 10
# 只保留最后一个列
> drunk %>%
+ transmute(older_than_30 = `30-39` + `40-49` + `50-59` + `60+`)
older_than_30
1 718
2 40
浙公网安备 33010602011771号