R之dplyr::select/mutate函数扩展

select函数

dplyr包select函数用的很多,不过我们一般也是通过正反选列名或数字来选择列。
iris数据集
常见用法如:

select(iris,c(1,3))
select(iris,1,3) #同上
select(iris,1:3)
select(iris,-c(1,3))

select(iris, Sepal.Length, Sepal.Width)
select(iris, Sepal.Length:Species)  
select(iris, -Sepal.Length, -Sepal.Width)
select(iris, one=Sepal.Length)

实际应用中我们加上一些辅助函数会更加得心应手。

这些函数有:

select(iris, starts_with("Sepal"))
select(iris, starts_with("sepal")) #默认忽略大小写
select(iris, starts_with("Sepal", ignore.case = F)) #区分大小写
select(iris, -starts_with("Sepal")) #同样可以反选
select(iris,name=starts_with("Sepal")) #重命名

select(iris, ends_with(“Length”)) # 选择列名以Length结尾的的列
select(iris, contains(“Sep”)) # 选择列名包含有Sep的列
select(iris, matches(“\.”)) #选择列名正则匹配到有’点’的列
select(iris, num_range(“Sepal.Length”, 1:5)) #选择列名为Sepal.Length1到Sepal.Length5的列
select(iris, one_of(“Sepal.Length”, “Sepal.Width”)) #选择列名为Sepal.Length和Sepal.Width的列
select(iris, everything()) #用于选择所有变量(列名),一般用于改变列名顺序用

mutate

mutate(iris,new=Sepal.Length*Sepal.Width) #在数据框后新增一列
transmute(iris,new=Sepal.Length*Sepal.Width) #另存为一个只有新增列的数据框

Ref: http://www.bioinfo-scrounger.com/archives/405
https://www.cnblogs.com/wkslearner/p/5741591.html

原文地址:https://www.cnblogs.com/jessepeng/p/11185976.html