第一次寫簡書,用Rmarkdown試試水御板!
木?——于2019.4.2
apply族函數(shù)
apply(X, MARGIN, FUN, ...)魁亦,MARGIN為維度,一般對數(shù)據(jù)框或矩陣邀摆,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類型數(shù)據(jù),輸出返回項也是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)汉额,函數(shù)項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"