apply()函数族
来源:互联网 发布:中国电信4g网络覆盖 编辑:程序博客网 时间:2024/04/30 18:13
apply()函数族:
apply():该函数只能运用于矩阵。(若是数据框,它会自动将其转化成矩阵。)
该函数三个参数,第一个是矩阵,第二个是数字1或者2,1代表处理行,2代表列,第三个函数代表调用的处理函数。
> t<-matrix(1:9,nrow=3)
> t
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> apply(t,2,sum)
[1] 6 15 24
> ########该例子,求取的各个列之和。
R自带的行列求取函数:colSums(),rowSums()
例子:rowSums(matrix,as.rm=TRUE)##该函数删除所有是NA的元素求和。
lapply():该函数的工作原理是讲一个函数运用到一个列表中的,每一个元素,并将结果作为列表返回。
例子:
> thelist
[[1]]
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[[2]]
[1] 1 2 3 4 5
[[3]]
[1] 2
> lapply(thelist,sum)
[[1]]
[1] 45
[[2]]
[1] 15
[[3]]
[1] 2
用sapply()函数将lapply的结果转化成向量,sapply()函数跟lapply函数很像,使用方法以及操作运算都一样,唯一是返回类型不一样。lapply返回列表,sapply返回向量。
aggregate(property1~property2+property3+..,mydataframe,function)
该函数将汇总与分组运算作为他们的第一次R任务。
~左侧的为亚奥操作的变量,右侧为分组依据,可以使一个或者多个变量。
第二个参数为数据来源,第三个参数为应用于分组的函数
若是汇总两个变量以及以上:
aggregate(cbind(property1,property)~property2+property3+..,mydataframe,function)##使用列联函数cbind.
aggregate()函数:将汇总跟分组作为一次R任务。
library(ggplot2)##加载该包,内置了diamonds数据集,钻石信息
> head(diamonds)
carat cut color clarity depth table price x y z
1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43
2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31
3 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31
4 0.29 Premium I VS2 62.4 58 334 4.20 4.23 2.63
5 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75
6 0.24 Very Good J VVS2 62.8 57 336 3.94 3.96 2.48
##该函数的第一个参数,~左侧为要操作的变量,右侧为分割依据,第三个参数为数据集,第四个为调用函数。
> aggregate(price~cut,diamonds,mean)##按照cut分组来多price进行mean操作,数据集是diamonds.
cut price
1 Fair 4358.758
2 Good 3928.864
3 Very Good 3981.760
4 Premium 4584.258
5 Ideal 3457.542
>##### aggregate(price~cut+color,diamonds,mean),如果使用多个分割方案的话,在formula的右侧(~),用+连接属性名就可以
aggregate(cbind(price,carat)~cut+color,diamonds,mean) ##若是休要汇总两个变量,用cbind(x,y)进行列整合。
cut color price carat
1 Fair D 4291.061 0.9201227
2 Good D 3405.382 0.7445166
3 Very Good D 3470.467 0.6964243
4 Premium D 3631.293 0.7215471
5 Ideal D 2629.095 0.5657657
6 Fair E 3682.312 0.8566071
0 0
- apply函数族
- apply()函数族
- apply函数族简介
- 【R语言】apply函数族
- R语言apply函数族笔记
- R语言apply函数族笔记
- R语言apply族函数详解
- 掌握R语言中的apply函数族
- 第三章第一节 apply族函数
- call与apply函数
- extjs apply函数用法
- python apply()函数
- R:矩阵apply()函数
- python apply()函数
- apply函数-学习
- python apply()函数
- apply call函数
- python apply()函数
- Codeforces 217E Alien DNA (树状数组求第k大)
- eclipse中查看框架的源码方式
- DES密码算法
- java 用String类实现十进制转二进制
- leetcode 103. Binary Tree Zigzag Level Order Traversal-深度遍历|广度遍历|递归|非递归
- apply()函数族
- 【Mysql】建立第一个存储过程
- NYOJ 27 水池数目 (BFS,DFS)
- 安卓学习计划
- HDU 1017 A Mathematical Curiosity
- Android Dialog 系统样式讲解及透明背景
- C++第6次作业
- Android Studio发布项目到Jcenter
- Spark streaming源码分析之Job动态生成原理与源码解析