如何查找按2个不同列分组的四分位数

时间:2012-11-24 01:13:40

标签: r statistics quantile

我有一个看起来像这样的数据集

year month age
2007 1     17
2007 1     18
2007 1     19
2007 1     30
2007 1     31
2007 2     18
2007 2     19
2007 2     30
2008 2     41
2008 2     52
2008 2     49  
2008 3     23
2008 3     19
2008 3     39

我每年和每月都试图找到四分位组。

结果应该是:

2007 1 Q1 Q2 Q3 Q4
2007 2 Q1 Q2 Q3 Q4

等。

由于

2 个答案:

答案 0 :(得分:4)

Aggregate会这样做。

> aggregate(.~year + month, data=age, FUN=fivenum)
  year month age.1 age.2 age.3 age.4 age.5
1 2007     1  17.0  18.0  19.0  30.0  31.0
2 2007     2  18.0  18.5  19.0  24.5  30.0
3 2008     2  41.0  45.0  49.0  50.5  52.0
4 2008     3  19.0  21.0  23.0  31.0  39.0


> dput(age)
structure(list(year = c(2007L, 2007L, 2007L, 2007L, 2007L, 2007L, 
2007L, 2007L, 2008L, 2008L, 2008L, 2008L, 2008L, 2008L), month = c(1L, 
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L), age = c(17L, 
18L, 19L, 30L, 31L, 18L, 19L, 30L, 41L, 52L, 49L, 23L, 19L, 39L
)), .Names = c("year", "month", "age"), class = "data.frame", row.names = c(NA, 
-14L))

答案 1 :(得分:3)

你的问题有点令人困惑。它只需要三个切点就可以分成四分位数。那么在Q1,Q2,Q3,Q4列中您真正想要的是什么?如果你想要数,那似乎有点无聊。我假设你想要min,25th.pctile,中位数,75th.pctile和max:

do.call ( rbind, with( dfrm, tapply(age, interaction(year=year , month=month), quantile, 
                                                           probs=c(0, .25,.5, 0.75, 1) ) ) )
#---------------------
       0%  25% 50%  75% 100%
2007.1 17 18.0  19 30.0   31
2007.2 18 18.5  19 24.5   30
2008.2 41 45.0  49 50.5   52
2008.3 19 21.0  23 31.0   39
相关问题