R语言:apply族函数(一)

apply函数族的函数对数组(二维或者多维)或者矩阵的某个子集进行行、列或者第三维的迭代操作,返回相关结果。

apply函数族有apply,lapply,sapply,tapply,mapply等等函数,每一个函数都有自己特有的功能。

1 apply

用法:apply(array, margin, fun,...)  margin=1,2,3,...,通过fun函数对行(margin=1)、列(margin=2)或者第三维(margin=3)进行统计。也可以添加其它参数,如na.rm=TRUE会去掉数据为NA的项在进行统计。

> a <- array(c(1:24),dim=c(2,3,4))
> a
, , 1

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

, , 2

     [,1] [,2] [,3]
[1,]    7    9   11
[2,]    8   10   12

, , 3

     [,1] [,2] [,3]
[1,]   13   15   17
[2,]   14   16   18

, , 4

     [,1] [,2] [,3]
[1,]   19   21   23
[2,]   20   22   24

> apply(a,1,sum)  #按行统计数据总和
[1] 144 156
> apply(a,2,sum)  #按列统计数据总和
[1]  84 100 116
> apply(a,3,sum)  #这里array是三维,按照第三维度统计总和
[1]  21  57  93 129

2 lapply

    lapply(list,fun,...)    lapply对list每列或者vector进行操作,返回list对象

> b <- list(x=1:24,y=25:48) 
> b
$x
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

$y
 [1] 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

> lapply(b,mean)
$x
[1] 12.5

$y
[1] 36.5

> lapply(b,function(x)x+3)
$x
 [1]  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

$y
 [1] 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

3 sapply

sapply(list, fun,simplify=TRUE)    ,跟lapply函数类似使用,也是处理列表或者向量数据,它和lapply函数不同之处在于其返回的是向量,若返回结果长度大于1则返回matrix。若simplify=FALSE则返回list,跟lapply函数一样。

> b <- list(x=1:24,y=25:48) 
> sapply(b,mean)
   x    y 
12.5 36.5 
> sapply(b,mean,simplify=FALSE)
$x
[1] 12.5

$y
[1] 36.5

> sapply(b,function(x)x+3)[1:5,]
     x  y
[1,] 4 28
[2,] 5 29
[3,] 6 30
[4,] 7 31
[5,] 8 32

4 tapply

 tapply 对向量进行分组统计

使用方法:tapply(vector, indices, fun)

> fac <- factor(rep(1:4,length=24),levels=1:6)
> fac
 [1] 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
Levels: 1 2 3 4 5 6
> tapply(1:24,fac,sum)
 1  2  3  4  5  6 
66 72 78 84 NA NA

5 mapply

mapply函数在fun后可以接受多个数据,fun分别利用这些数据的第一个元素进行统计返回,再利用第二个元素统计返回,直到没有元素了为止,返回列表结果。

> mapply(sum,1:10,11:20)
 [1] 12 14 16 18 20 22 24 26 28 30
> mapply(function(x,y)x+y,1:10,11:20)
 [1] 12 14 16 18 20 22 24 26 28 30
> mapply(function(x,y)c(x+y,x*y),1:10,11:20)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]   12   14   16   18   20   22   24   26   28    30
[2,]   11   24   39   56   75   96  119  144  171   200

> mapply(rep,times=1:4,x=4:1)
[[1]]
[1] 4

[[2]]
[1] 3 3

[[3]]
[1] 2 2 2

[[4]]
[1] 1 1 1 1

> rep(times=1:4,x=4:1)
 [1] 4 3 3 2 2 2 1 1 1 1

猜你喜欢

转载自blog.csdn.net/sinat_41624848/article/details/83117931