## 데이터를 조건에 맞게 그룹으로 분할
ddply(diamonds, .(cut), summarise, priceMean=mean(price))
## diamond_df를 cut을 기준으로 그룹화
df=group_by(diamonds_df, cut)
Source: local data frame [53,940 x 10]
Groups: cut ## cut으로 그룹화 되어있는 것을 볼 수 있다.
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
7 0.24 Very Good I VVS1 62.3 57 336 3.95 3.98 2.47
8 0.26 Very Good H SI1 61.9 55 337 4.07 4.11 2.53
9 0.22 Fair E VS2 65.1 61 337 3.87 3.78 2.49
10 0.23 Very Good H VS1 59.4 61 338 4.00 4.05 2.39
.. ... ... ... ... ... ... ... ... ... ...
## 그룹화된 데이터를 가지고 summarise()함수를 이용해 price의 평균을 구해보자
summarise(df, meanPrice=mean(price, na.rm=TRUE))
Source: local data frame [5 x 2]
cut meanPrice
1 Fair 4358.758
2 Good 3928.864
3 Very Good 3981.760
4 Premium 4584.258
5 Ideal 3457.542
summarise(df, N=n(), meanPrice=mean(price)) ## n()함수는 그룹별로 관찰값들의 개수
Source: local data frame [5 x 3]
cut N meanPrice
1 Fair 1610 4358.758
2 Good 4906 3928.864
3 Very Good 12082 3981.760
4 Premium 13791 4584.258
5 Ideal 21551 3457.542
'R Programming > R Function' 카테고리의 다른 글
패키지 업데이트 (0) | 2015.03.27 |
---|---|
nchar() 함수 (0) | 2015.03.12 |
lapply(), sapply(), length() (0) | 2015.03.12 |
RStudio 관련 TIP (0) | 2015.03.06 |
RStudio 단축키 (0) | 2015.03.06 |