mutate()
函数增加新变量并保留原变量;transmute()
函数增加新变量并删除原变量,新变量覆盖原来重名变量。也可以设置变量值为NULL删除变量。
> df <- iris[c(1,2,3,4)]#载入鸢尾花数据集
> head(df)
Sepal.Length Sepal.Width Petal.Length Petal.Width
1 5.1 3.5 1.4 0.2
2 4.9 3.0 1.4 0.2
3 4.7 3.2 1.3 0.2
4 4.6 3.1 1.5 0.2
5 5.0 3.6 1.4 0.2
6 5.4 3.9 1.7 0.4
> #transmute()函数的使用,选定的列会被重新命名并覆盖,未被选择的则会被舍弃。
> df_transmute <- df %>% transmute(lenth=Sepal.Length,
+ width=Sepal.Width)
> head(df_transmute)
lenth width
1 5.1 3.5
2 4.9 3.0
3 4.7 3.2
4 4.6 3.1
5 5.0 3.6
6 5.4 3.9
> #mutate
> df_mutate <- df %>% mutate(new_col="lenth"
+ )
> head(df_mutate)
Sepal.Length Sepal.Width Petal.Length Petal.Width new_col
1 5.1 3.5 1.4 0.2 lenth
2 4.9 3.0 1.4 0.2 lenth
3 4.7 3.2 1.3 0.2 lenth
4 4.6 3.1 1.5 0.2 lenth
5 5.0 3.6 1.4 0.2 lenth
6 5.4 3.9 1.7 0.4 lenth
>