第一次写简书,用Rmarkdown试试水!
木䬕——于2019.4.2
apply族函数
apply(X, MARGIN, FUN, ...),MARGIN为维度,一般对数据框或矩阵,1代表行,2 代表列
> apply(iris[,1:4],2,mean) -> a
>a
Sepal.Length Sepal.Width Petal.Length Petal.Width
5.843333 3.057333 3.758000 1.199333
> class(a)#numeric
[1] "numeric"
lapply(X, FUN, ...),X可以为list类型数据,输出返回项也是list
> lapply(iris[,1:4],mean) -> b
> b
$Sepal.Length
[1] 5.843333
$Sepal.Width
[1] 3.057333
$Petal.Length
[1] 3.758
$Petal.Width
[1] 1.199333
> class(b)#list
[1] "list"
> unlist(b) -> c
> c
Sepal.Length Sepal.Width Petal.Length Petal.Width
5.843333 3.057333 3.758000 1.199333
> class(c)
[1] "numeric"
> split(iris$Sepal.Length,iris$Species) -> d
> d
$setosa
[1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 4.8 4.3 5.8 5.7 5.4 5.1 5.7 5.1 5.4 5.1 4.6
[24] 5.1 4.8 5.0 5.0 5.2 5.2 4.7 4.8 5.4 5.2 5.5 4.9 5.0 5.5 4.9 4.4 5.1 5.0 4.5 4.4 5.0 5.1 4.8
[47] 5.1 4.6 5.3 5.0
$versicolor
[1] 7.0 6.4 6.9 5.5 6.5 5.7 6.3 4.9 6.6 5.2 5.0 5.9 6.0 6.1 5.6 6.7 5.6 5.8 6.2 5.6 5.9 6.1 6.3
[24] 6.1 6.4 6.6 6.8 6.7 6.0 5.7 5.5 5.5 5.8 6.0 5.4 6.0 6.7 6.3 5.6 5.5 5.5 6.1 5.8 5.0 5.6 5.7
[47] 5.7 6.2 5.1 5.7
$virginica
[1] 6.3 5.8 7.1 6.3 6.5 7.6 4.9 7.3 6.7 7.2 6.5 6.4 6.8 5.7 5.8 6.4 6.5 7.7 7.7 6.0 6.9 5.6 7.7
[24] 6.3 6.7 7.2 6.2 6.1 6.4 7.2 7.4 7.9 6.4 6.3 6.1 7.7 6.3 6.4 6.0 6.9 6.7 6.9 5.8 6.8 6.7 6.7
[47] 6.3 6.5 6.2 5.9
> class(d)#list
[1] "list"
> lapply(d,mean)
$setosa
[1] 5.006
$versicolor
[1] 5.936
$virginica
[1] 6.588
sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE),与lapply用法相似,但返回项不同,非list类型
> sapply(d,mean)-> e
> e
setosa versicolor virginica
5.006 5.936 6.588
> class(e)#numeric
[1] "numeric"
tapply(X, INDEX, FUN = NULL, ..., default = NA, simplify = TRUE),返回项array类型
> tapply(iris$Sepal.Length,list(iris$Species),mean) -> f
> f
setosa versicolor virginica
5.006 5.936 6.588
> class(f)#"array"
[1] "array"
mapply(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE,USE.NAMES = TRUE),函数项FUN在前,与sapply类似
> mapply(mean,iris[,1:4])-> g
> g
Sepal.Length Sepal.Width Petal.Length Petal.Width
5.843333 3.057333 3.758000 1.199333
> class(g)#numeric
[1] "numeric"