【R笔记】apply函数族

 
(1)    apply
apply函数通过对数组,矩阵,或非空维数值的数据框的“边缘”(margin)即行或列运用函数。返回值为向量,数组或列表。
 
函数形式
apply(X, MARGIN, FUN, ...)
其中,X:数组(矩阵);
MARGIN:函数要作用的下标向量,对于矩阵,1表示行,2表示列,1:2表示行和列;
FUN:函数名或函数表达式。
 
 
##例
> m<-matrix(c(1:4,1,4,1:6),ncol=3)
> apply(m,1,mean)
[1] 1.666667 3.333333 3.000000 4.000000
> apply(m,2,sd)
[1] 1.290994 1.414214 1.290994
> apply(m,1:2,function(x) x*2)
     [,1] [,2] [,3]
[1,] 2 2 6
[2,] 4 8 8
[3,] 6 2 10
[4,] 8 4 12
> apply(m,2,table) #返回的是列表
[ [1] ]
 
1 2 3 4
1 1 1 1
……
> apply(m, 1, stats::quantile) #各行的分位数,返回矩阵
     [,1] [,2] [,3] [,4]
0% 1 2 1 2
25% 1 3 2 3
50% 1 4 3 4
75% 2 4 4 5
100% 3 4 5 6
 
 
(2)    by
 
  by函数是tapply的一个面向用户的友好包装版,是一个使用因子来对数据框按行进行分组并对每个子集运用函数的方法。它的对象数据被默认强制转换为数据框。它返回一个 类属性为by的对象,simplify i= false是,返回值是列表,否则是列表或数组。
by(data, INDICES, FUN, ..., simplify = TRUE)
 
#例 使用著名的鸢尾花数据iris
> attach(iris)
> head(iris)
   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
> by(iris[, 1:4], Species, mean)
Species: setosa
Sepal.Length Sepal.Width Petal.Length Petal.Width
       5.006 3.428 1.462 0.246
---------------------------------------------------------
Species: versicolor
Sepal.Length Sepal.Width Petal.Length Petal.Width
       5.936 2.770 4.260 1.326
---------------------------------------------------------
Species: virginica
Sepal.Length Sepal.Width Petal.Length Petal.Width
       6.588 2.974 5.552 2.026
 
 





posted @ 2016-03-23 10:59  萱草yy  阅读(501)  评论(0编辑  收藏  举报