R语言plyr包和dplyr包学习

时间:2022-09-07 11:57:10

apply族函数是R语言中很有特色的一类函数,包括了apply、sapply、lapply、tapply、aggregate等等。在这篇博文里对它们进行了简略的说明。这一类函数本质上是将数据进行分割、计算和整合。它们在数据分析的各个阶段都有很好的用处。例如在数据准备阶段,我们可以按某个标准将数据分组,然后获得各组的统计描述。或是在建模阶段,为不同组的数据建立模型并比较建模结果。apply族函数与Google提出的mapreduce策略有着一致的思路。因为mapreduce的思路也是将数据进行分割、计算和整合。只不过它是将分割后的数据分发给多个处理核心进行运算。如果你熟悉了apply族函数,那么将数据转为并行运算是轻而易举的事情。plyr包则可看作是apply族函数的扩展,使之更容易运用,功能更为强大。其官方解释为The plyr package is a set of clean and consistent tools that implement the split-apply-combine pattern in R. This is an extremely common pattern in data analysis: you solve a complex problem by breaking it down into small pieces, doing something to each piece and then combining the results back together again.

plyr包的主函数是**ply形式的,其中首字母可以是(d、l、a),第二个字母可以是(d、l、a、),不同的字母表示不同的数据格式,d表示数据框格式,l表示列表,a表示数组,则表示没有输出。第一个字母表示输入的待处理的数据格式,第二个字母表示输出的数据格式。例如ddply函数,即表示输入一个数据框,输出也是一个数据框。[2]

下面是应用
install.packages(“dplyr”)
library(plyr)
library(reshape2)
install.packages(“Lahman”)
library(Lahman) : Lahman 包里的棒球比赛数据集 Batting
This package provides the tables from Sean Lahman’s Baseball Database as a set of R data.frames. It uses the data on pitching, hitting and fielding performance and other tables from 1871 through 2013, as recorded in the 2014 version of the database.
install.packages(“hflights”)
library(hflights) : hflights 包里的飞机航班数据
library(plyr)
library(reshape2)

ref:
1:http://bbs.pinggu.org/thread-2250439-1-1.html
2.http://www.dataguru.cn/thread-311303-1-1.html
3.