1. [원] 통계상담 2014-11
A.2 R 데이터 다루기
reshape, plyr, data.table packages
허 명 회 (고려대 교수, 통계학)
2014.04.04
Hadley Wickham at UseR! 2013:
Author of reshape, plyr, ggplot2, ...
응 용 데 이 터 분 석 : R의 활용
2. [원] 통계상담 2014-12
개 요
R에서 loop를 사용하지 않는 효율적인 데이터 처리 방법들
1. reshape 형태 전환
2. plyr 분리-적용-합체 (split-apply-combine)
3. data.table 검색
3. [원] 통계상담 2014-13
: reshape
데이터세트의 형태 전환
사례: french_fries {reshape}
구조 time treatment subject rep y1 y2 y3 y4 y5
5개 반응
2회 반복
12명 피험자
3개 처리
10개 시점
* 다수의 결측
* 행 순서 임의화
4. [원] 통계상담 2014-14
: reshape
사례: french_fries 계속
목표 subject 별로 treatment에 따른 5개 y 반응의 평균 구하기
subject = : treatment y1 y2 y3 y4 y5
1 □ □ □ □ □
2 □ □ □ □ □
3 □ □ □ □ □
13. [원] 통계상담 2014-113
: plyr
Split-Apply-Combine
split apply combine
data a function outputs
하둡: Map Reduce
14. [원] 통계상담 2014-114
: plyr
사례: baseball {plyr}
구조 data.frame: 21699 obs. of 22 variables
$ id : ch "ansonca01" "forceda01" "mathebo01" "startjo01" ...
$ year : int 1871 1871 1871 1871 1871 1871 1871 1872 ...
$ rbi : int 16 29 10 34 23 21 23 50 15 16 ...
목표 id (선수) 별 career high rbi year 구하기
- c.year (= year-min(year)+1)
- max.rbi
절차 1. split – 전체자료를 id (선수) 별로 나누기
2. apply – id 별 subset에서 c.year와 max.rbi, 그것의 c.year를 구하기
3. combine – 앞의 결과를 합체하기
15. [원] 통계상담 2014-115
: plyr
사례: baseball 계속
# plyr for baseball data
library(plyr)
str(baseball)
calculate_c.year <- function(df) mutate(df, cyear = year - min(year)+1)
baseball.1 <- ddply(baseball, .(id), calculate_c.year)
## 데이터프레임 baseball의 오른쪽에 cyear가 붙는다.
calculate_c.rbi <- function(df)
c(best.year=df$cyear[which.max(df$rbi)], best.rbi=max(df$rbi), career.year=max(df$cyear))
bb.2 <- ddply(baseball.1, .(id), calculate_c.rbi)
str(bb.2)
## 데이터프레임 bb.2는 4개 변수로 구성된다: id, best.year, best.rbi, career.year
## 데이터프레임 bb.2의 개체 수는 1,228 (=선수 수)이다.
16. [원] 통계상담 2014-116
: plyr
사례: baseball 계속
# histograms of best.year and career.year
max(bb.2$career.year)
hist(bb.2$best.year, breaks=seq(0.5,40.5,1), xlab="best.year", main="")
hist(bb.2$career.year, breaks=seq(0.5,40.5,1), xlab="career.year", main="")
## max.rbi 분포의 mode는 7년차
17. [원] 통계상담 2014-117
: plyr
**ply
출력
array df list
입력
array aaply adply alply
df daply ddply dlply
list laply ldaply llaply
19. [원] 통계상담 2014-119
: data.table
효율적인 검색
1. Data Table 만들기: 6개의 random digit column과 1개의 수치 열로 구성된
10,000,000*7 데이터프레임
library(data.table)
n <- 10000000
digits <- as.factor(0:9)
x1 <- sample(digits, n, replace=T)
x2 <- sample(digits, n, replace=T)
x3 <- sample(digits, n, replace=T)
x4 <- sample(digits, n, replace=T)
x5 <- sample(digits, n, replace=T)
x6 <- sample(digits, n, replace=T)
DT <- data.table(x1, x2, x3, x4, x5, x6, y=rnorm(n))
23. [원] 통계상담 2014-123
: data.table
검색: 다른 방법
> p.time <- proc.time()
> DT[x1=="1" & x2=="2" & x3=="3" & x4=="4" & x5=="5" & x6=="6",]
⋮
> proc.time() - p.time
user system elapsed
8.47 1.06 9.63
비교: 앞 방법의 처리 시간
> proc.time() - p.time
user system elapsed
0.08 0.03 0.11 * elapsed time 기준 기존 방법 대비 1.1%에 불과,
* data.table이 binary search를 하기 때문.
24. [원] 통계상담 2014-124
정리⋅요약
데이터 다루기: “빅” 데이터 분석의 기초 (fundamentals)
통계학 전공자의 취약점
데이터 과학으로 진화하기 위해 넘어야 할 벽
참고문헌: R Manuals, Vignettes, ...
Journal of Statistical Software Papers
전희원 (2013). R로 하는 데이터 시각화. 한빛미디어
실습 파일: reshape_ff.r plyr_bb.r datatale_sim.r