R语言利器之ddply和aggregate

  ddply和aggregate是两个用来整合数据的功能强大的函数。

  aggregate(x, ...)

  关于aggregate()函数的使用在《R语言实战》中P105有简单描述,这里重新说一下。此函数主要有一下几种用法:
  

    ## Default S3 method:
  aggregate(x, ...)

  ## S3 method for class ‘data.frame‘
  aggregate(x, by, FUN, ..., simplify = TRUE, drop = TRUE)

  ## S3 method for class ‘formula‘
  aggregate(formula, data, FUN, ...,subset, na.action = na.omit)

  ## S3 method for class ‘ts‘
  aggregate(x, nfrequency = 1, FUN = sum, ndeltat = 1,ts.eps = getOption("ts.eps"), ...)

例:    

attach(mtcars)
aggdata <-aggregate(mtcars, by=list(cyl,gear), FUN=mean, na.rm=TRUE)
aggdata
 Group.1 Group.2    mpg cyl     disp       hp     drat       wt    qsec  vs   am gear     carb
1       4       3 21.500   4 120.1000  97.0000 3.700000 2.465000 20.0100 1.0 0.00    3 1.000000
2       6       3 19.750   6 241.5000 107.5000 2.920000 3.337500 19.8300 1.0 0.00    3 1.000000
3       8       3 15.050   8 357.6167 194.1667 3.120833 4.104083 17.1425 0.0 0.00    3 3.083333
4       4       4 26.925   4 102.6250  76.0000 4.110000 2.378125 19.6125 1.0 0.75    4 1.500000
5       6       4 19.750   6 163.8000 116.5000 3.910000 3.093750 17.6700 0.5 0.50    4 4.000000
6       4       5 28.200   4 107.7000 102.0000 4.100000 1.826500 16.8000 0.5 1.00    5 2.000000
7       6       5 19.700   6 145.0000 175.0000 3.620000 2.770000 15.5000 0.0 1.00    5 6.000000
8       8       5 15.400   8 326.0000 299.5000 3.880000 3.370000 14.5500 0.0 1.00    5 6.000000

  得到数据框aggdata,其中的Group.1和Group.2的列名可以指定,只需第二行写成:

aggdata <-aggregate(mtcars, by=list(Group.cyl=cyl, Group.gears=gear),FUN=mean, na.rm=TRUE)

即可。

  注意:在使用aggregate()函数的时候, by中的变量必须在一个列表中(即使只有一个变量) 。 指定的函数FUN可为任意的内建或自编函数 。

  其他的一些例子:  

## Compute the averages for the variables in ‘state.x77‘, grouped
## according to the region (Northeast, South, North Central, West) that
## each state belongs to.
aggregate(state.x77, list(Region = state.region), mean)
## Compute the averages according to region and the occurrence of more
## than 130 days of frost.
aggregate(state.x77,
          list(Region = state.region,Cold = state.x77[,"Frost"] > 130),
          mean)
## (Note that no state in ‘South‘ is THAT cold.)
## example with character variables and NAs
testDF <- data.frame(v1 = c(1,3,5,7,8,3,5,NA,4,5,7,9),
                     v2 = c(11,33,55,77,88,33,55,NA,44,55,77,99) )
by1 <- c("red", "blue", 1, 2, NA, "big", 1, 2, "red", 1, NA, 12)
by2 <- c("wet", "dry", 99, 95, NA, "damp", 95, 99, "red", 99, NA, NA)
aggregate(x = testDF, by = list(by1, by2), FUN = "mean")
# and if you want to treat NAs as a group
fby1 <- factor(by1, exclude = "")
fby2 <- factor(by2, exclude = "")
aggregate(x = testDF, by = list(fby1, fby2), FUN = "mean")
## Formulas, one ~ one, one ~ many, many ~ one, and many ~ many:
aggregate(weight ~ feed, data = chickwts, mean)
aggregate(breaks ~ wool + tension, data = warpbreaks, mean)
aggregate(cbind(Ozone, Temp) ~ Month, data = airquality, mean)
aggregate(cbind(ncases, ncontrols) ~ alcgp + tobgp, data = esoph, sum)
## Dot notation:
aggregate(. ~ Species, data = iris, mean)
aggregate(len ~ ., data = ToothGrowth, mean)
## Often followed by xtabs():
ag <- aggregate(len ~ ., data = ToothGrowth, mean)
xtabs(len ~ ., data = ag)
## Compute the average annual approval ratings for American presidents.
aggregate(presidents, nfrequency = 1, FUN = mean)
## Give the summer less weight.
aggregate(presidents, nfrequency = 1,
          FUN = weighted.mean, w = c(1, 1, 0.5, 1))

  ddply

  下面是ddply函数的一般用法:

ddply(.data, .variables, .fun = NULL, ..., .progress = "none",.inform = FALSE, .drop = TRUE, .parallel = FALSE, .paropts = NULL)

  例:

# Summarize a dataset by two variables
dfx <- data.frame(
  group = c(rep(‘A‘, 8), rep(‘B‘, 15), rep(‘C‘, 6)),
  sex = sample(c("M", "F"), size = 29, replace = TRUE),
  age = runif(n = 29, min = 18, max = 54)
)
head(dfx)
 group sex      age
1     A   M 22.44750
2     A   M 52.92616
3     A   F 30.00443
4     A   M 39.56907
5     A   M 18.89180
6     A   F 50.81139
#Note the use of the ‘.‘ function to allow
# group and sex to be used without quoting
ddply(dfx, .(group, sex), summarize,mean = round(mean(age), 2),sd = round(sd(age), 2))
  group sex  mean    sd
1     A   F 40.41 14.71
2     A   M 30.35 13.17
3     B   F 34.81 12.76
4     B   M 34.04 13.36
5     C   F 35.09 13.39
6     C   M 28.53  4.57
# An example using a formula for .variables
ddply(baseball[1:100,], ~ year, nrow)
 year V1
1 1871  7
2 1872 13
3 1873 13
4 1874 15
5 1875 17
6 1876 15
7 1877 17
8 1878  3
# Applying two functions; nrow and ncol
ddply(baseball, .(lg), c("nrow", "ncol"))
 lg  nrow ncol
1       65   22
2 AA   171   22
3 AL 10007   22
4 FL    37   22
5 NL 11378   22
6 PL    32   22
7 UA     9   22
# Calculate mean runs batted in for each year
rbi <- ddply(baseball, .(year), summarise,mean_rbi = mean(rbi, na.rm = TRUE))
head(rbi)
  year mean_rbi
1 1871 22.28571
2 1872 20.53846
3 1873 30.92308
4 1874 29.00000
5 1875 31.58824
6 1876 30.13333
# Plot a line chart of the result
plot(mean_rbi ~ year, type = "l", data = rbi)
# make new variable career_year based on the
# start year for each player (id)
base2 <- ddply(baseball, .(id), mutate,career_year = year - min(year) + 1)
head(base2)
         id year stint team lg   g  ab   r   h X2b X3b hr rbi sb cs bb so ibb hbp sh sf gidp career_year
1 aaronha01 1954     1  ML1 NL 122 468  58 131  27   6 13  69  2  2 28 39  NA   3  6  4   13           1
2 aaronha01 1955     1  ML1 NL 153 602 105 189  37   9 27 106  3  1 49 61   5   3  7  4   20           2
3 aaronha01 1956     1  ML1 NL 153 609 106 200  34  14 26  92  2  4 37 54   6   2  5  7   21           3
4 aaronha01 1957     1  ML1 NL 151 615 118 198  27   6 44 132  1  1 57 58  15   0  0  3   13           4
5 aaronha01 1958     1  ML1 NL 153 601 109 196  34   4 30  95  4  1 59 49  16   1  0  3   21           5
6 aaronha01 1959     1  ML1 NL 154 629 116 223  46   7 39 123  8  0 51 54  17   4  0  9   19           6
时间: 2024-08-02 10:43:05

R语言利器之ddply和aggregate的相关文章

R语言学习资源

入门视频教程 R语言初级课程(1)- R语言快速入门http://cos.name/videos/intro-2-r/ 代码 #对象 1+1*3 c(1,2,3,4,5) c('helloworld','i am a R user') c("hehe","haha") 1:6 6:1 exp(1:4) log(1:3) a<-c(1,2,3,4,5) a[1] a[1:3] a[-4] a>3 a[a>3] #数组,类型需要一致 x<-1:1

Linux菜鸟升级利器之ansible

一.absible是什么? ansible是一款简单的.开源的自动化管理工具.它通过Openssh工作,没有服务器:并且被管理的客户端上面并不需要安装什么客户端软件或启动什么守护进程,没有客户端:扩展模块可以使用任何语言编写:命令自动传输到管理机执行,并返回结果: 二.安装ansible 安装ansible需要使用Fedora的EPEL源,所以要先配置好yum的epel源,在yum源文件中添加: [base1] name=epel baseurl=http://dl.fedoraproject.

R语言进阶之4:数据整形(reshape)

一.通过重新构建数据进行整形 数据整形最直接的思路就把数据全部向量化,然后按要求用向量构建其他类型的数据.这样是不是会产生大量的中间变量.占用大量内存?没错.R语言的任何函数(包括赋值)操作都会有同样的问题,因为R函数的参数传递方式是传值不传址,变量不可能原地址修改后再放回原地址. 矩阵和多维数组的向量化有直接的类型转换函数: as.vector,向量化后的结果顺序是先列后行再其他: > (x <- matrix(1:4, ncol=2))  #为节省空间,下面的结果省略了一些空行 [,1] 

[译]用R语言做挖掘数据《七》

时间序列与数据挖掘 一.实验说明 1. 环境登录 无需密码自动登录,系统用户名shiyanlou,密码shiyanlou 2. 环境介绍 本实验环境采用带桌面的Ubuntu Linux环境,实验中会用到: 1. LX终端(LXTerminal): Linux命令行终端,打开后会进入Bash环境,可以使用Linux命令2. GVim:非常好用的编辑器,最简单的用法可以参考课程Vim编辑器3. R:在命令行输入‘R’进入交互式环境,下面的代码都是在交互式环境运行4. 数据:在命令行终端输入以下命令:

R语言基因组数据分析可能会用到的data.table函数整理

R语言data.table包是自带包data.frame的升级版,用于数据框格式数据的处理,最大的特点快.包括两个方面,一方面是写的快,代码简洁,只要一行命令就可以完成诸多任务,另一方面是处理快,内部处理的步骤进行了程序上的优化,使用多线程,甚至很多函数是使用C写的,大大加快数据运行速度.因此,在对大数据处理上,使用data.table无疑具有极高的效率.这里主要介绍在基因组数据分析中可能会用到的函数. fread 做基因组数据分析时,常常需要读入处理大文件,这个时候我们就可以舍弃read.ta

R语言实战(五)方差分析与功效分析

本文对应<R语言实战>第9章:方差分析:第10章:功效分析 ==================================================================== 方差分析: 回归分析是通过量化的预测变量来预测量化的响应变量,而解释变量里含有名义型或有序型因子变量时,我们关注的重点通常会从预测转向组别差异的分析,这种分析方法就是方差分析(ANOVA).因变量不只一个时,称为多元方差分析(MANOVA).有协变量时,称为协方差分析(ANCOVA)或多元协方差分析

《R语言实战》学习笔记seventh

由于在准备软考中级数据库系统工程师外加巩固SQL Server 2012,所以拖了好久一直没继续学R 下去 所以今天重开R 的战事 这次是关于基本统计分析的内容,即关于用于生成基本的描述性统计量和推断统计量的R 函数 首先,将着眼于定量变量的位置和尺度的衡量方式 然后将是生成类别型变量的频数表和列联表的方法(以及连带的卡方检验) 接下来将考察连续型和有序型变量相关系数的多种形式 最后转而通过参数检验(t检验)和非参数检验(Mann-Whitney U检验.Kruskal-Wallis检验)方法研

R语言基本备忘-统计分析

Part1 相关统计量说明 峰度系数Coefficientof kurtosis http://baike.baidu.com/link?url=gS_sgtNYSRdjLnadNWDDa357DIzJma-tdheAx5eKp0WzTvuH_PYg8hnMNIiP4-DRmewtftVQXXUbtIYzvz4bTq 峰度系数(Kurtosis)用来度量数据在中心聚集程度.在正态分布情况下,峰度系数值是3(但是SPSS等软件中将正态分布峰度值定为0,是因为已经减去3,这样比较起来方便).>3的峰

R语言编程艺术(2)R中的数据结构

本文对应<R语言编程艺术>第2章:向量:第3章:矩阵和数组:第4章:列表:第5章:数据框:第6章:因子和表 ========================================================================= R语言最基本的数据类型就是向量(vector),单个数值和矩阵都是向量的一种特例. 声明:R中不需要声明变量,但是注意函数式语言的特性,如果读写向量中的元素时,R事先不知道对象是向量的话,则函数没有执行的对象.如下代码是无法工作的: y[1]