R中利用apply、tapply、lapply、sapply、mapply
- apply函数(对一个数组按行或者按列进行计算):
示例代码:
> ma <- matrix(c(1:4, 1, 6:8), nrow = 2)
> ma
[,1] [,2] [,3] [,4]
[1,] 1 3 1 7
[2,] 2 4 6 8
> apply(ma, c(1,2), sum)
[,1] [,2] [,3] [,4]
[1,] 1 3 1 7
[2,] 2 4 6 8
> apply(ma, 1, sum)
[1] 12 20
> apply(ma, 2, sum)
[1] 3 7 7 15
- 函数tapply(进行分组统计):
示例代码:
> fac <- factor(rep(1:3, length = 17), levels = 1:5)
> fac
[1] 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2
Levels: 1 2 3 4 5
> tapply(1:17, fac, sum)
1 2 3 4 5
51 57 45 NA NA
> tapply(1:17, fac, sum, simplify = FALSE)
$`1`
[1] 51
$`2`
[1] 57
$`3`
[1] 45
$`4`
NULL
$`5`
NULL
> tapply(1:17, fac, range)
$`1`
[1] 1 16
$`2`
[1] 2 17
$`3`
[1] 3 15
$`4`
NULL
$`5`
NULL
#利用tapply实现类似于excel里的数据透视表的功能:
> da
year province sale
1 2007 A 1
2 2007 B 2
3 2007 C 3
4 2007 D 4
5 2008 A 5
6 2008 C 6
7 2008 D 7
8 2009 B 8
9 2009 C 9
10 2009 D 10
> attach(da)
> tapply(sale,list(year,province))
[1] 1 4 7 10 2 8 11 6 9 12
> tapply(sale,list(year,province),mean)
A B C D
2007 1 2 3 4
2008 5 NA 6 7
2009 NA 8 9 10
- 函数table(求因子出现的频数):
示例代码:
> d <- factor(rep(c("A","B","C"), 10), levels=c("A","B","C","D","E"))
> d
[1] A B C A B C A B C A B C A B C A B C A B C A B C A B C A B C
Levels: A B C D E
> table(d)
d
A B C D E
10 10 10 0 0
> table(d, exclude="B")
d
A C D E
10 10 0 0
- 函数lapply与函数sapply:
示例代码:
> x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE,FALSE,FALSE,TRUE))
> lapply(x, quantile)
$a
0% 25% 50% 75% 100%
1.00 3.25 5.50 7.75 10.00
$beta
0% 25% 50% 75% 100%
0.04978707 0.25160736 1.00000000 5.05366896 20.08553692
$logic
0% 25% 50% 75% 100%
0.0 0.0 0.5 1.0 1.0
> sapply(x, quantile,simplify=FALSE,use.names=FALSE)
$a
0% 25% 50% 75% 100%
1.00 3.25 5.50 7.75 10.00
$beta
0% 25% 50% 75% 100%
0.04978707 0.25160736 1.00000000 5.05366896 20.08553692
$logic
0% 25% 50% 75% 100%
0.0 0.0 0.5 1.0 1.0
#参数simplify=TRUE的情况
> sapply(x, quantile)
a beta logic
0% 1.00 0.04978707 0.0
25% 3.25 0.25160736 0.0
50% 5.50 1.00000000 0.5
75% 7.75 5.05366896 1.0
100% 10.00 20.08553692 1.0
- 函数mapply:
> 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的结果:
> rep(1:4,1:4)
[1] 1 2 2 3 3 3 4 4 4 4
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。