poorman包,在作者来看,他要做成dplyr包的copy版,但不需要其它依赖包,这是poorman包的初衷。也是我可能会喜欢这个包的原因所在。
R语言的强大在它有很多的程序包,同时,它的缺点是这些程序包往往又基于其它的程序包,导致在R语言或者某些程序包更新了,原有的程序包会出现无法使用的情况。
0 poorman包的安装
方法很简单,如下:
install.packages("poorman")
1 管道操作符%>%
管道操作符%>%是一个非常好用的操作符,可以有效减少代码。
示例1
library(poorman)
# head(iris)
> iris %>% head()
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
需要注意的是,%>%后面的函数,需要加上(),否则无法运行。这不同于dplyr包。
示例2
> iris[,-5] %>% correlation::correlation() %>% summary()
Parameter | Petal.Width | Petal.Length | Sepal.Width
-------------------------------------------------------
Sepal.Length | 0.82*** | 0.87*** | -0.12
Sepal.Width | -0.37*** | -0.43*** |
Petal.Length | 0.96*** | |
示例3
iris[,-5] %>% correlation::correlation() %>% qgraph::qgraph()
2 arrange排序
排序函数arrange,简单易用,变量默认按升序,加上-号按减序。
> iris %>% arrange(Sepal.Length,-Sepal.Width) %>% head(3)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
14 4.3 3.0 1.1 0.1 setosa
43 4.4 3.2 1.3 0.2 setosa
39 4.4 3.0 1.3 0.2 setosa
3 filter取行子集
filter用于选取数据行子集。
> iris %>% filter(Sepal.Length %in% c(4.3,4.4) )
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
9 4.4 2.9 1.4 0.2 setosa
14 4.3 3.0 1.1 0.1 setosa
39 4.4 3.0 1.3 0.2 setosa
43 4.4 3.2 1.3 0.2 setosa
4 select取列子集
select用于选取数据列子集。
> iris %>% select(Sepal.Length,Species) %>% head(3)
Sepal.Length Species
1 5.1 setosa
2 4.9 setosa
3 4.7 setosa
5 rename重命名
rename用于变量的重命名。
> iris %>% rename(SepL = Sepal.Length) %>% head(3)
SepL Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
6 summarise汇总
summarise用于数据汇总。
> iris %>% group_by(Species)%>%summarise(mean(Sepal.Length))
Species mean(Sepal.Length)
1 setosa 5.006
2 versicolor 5.936
3 virginica 6.588
Groups: Species
从上述来看,基本上dplyr包的功能,poorman都具备了。
myF<-function(x){
M=mean(x);SD=sd(x);N=length(x)
res=data.frame(M,SD,N)
names(res)<-c('mean','sd','no')
res
}
> iris %>% group_by(Species)%>% summarise(myF(Sepal.Length))
Species mean sd no
1 setosa 5.006 0.3524897 50
2 versicolor 5.936 0.5161711 50
3 virginica 6.588 0.6358796 50
最新版的poorman,已经可以使用自编函数。这是个很不错的改进!
感兴趣的朋友,可以试试这个poorman包。