R- ddply功能

时间:2015-02-25 22:57:01

标签: r

嘿大家我有一个大约8的数据集,我想为每个城市和年份的组合计算最大的数量。

数据集如下所示:

  city    sales    volume    year    avg price
  abilene 239      12313     2000    7879
  kansas  2324     18765     2000     2424
  nyc     2342     987651    2000     3127
  abilene 3432     34342     2001     1234
  nyc     2342     10000     2001     3127 
  kansas  176      3130     2001      879
  kansas  123      999650     2002    2424  
  abilene 3432     34342     2002     1234
  nyc     2342     98000    2002     3127 

我希望我的数据集看起来像这样:

city    year    volume
nyc     2000    987651    
abilene 2001    34342
kansas  2002    999650

我使用ddplyr查找每个城市的最大音量。

newdf=ddply(df,c('city','year'),summarise, max(volume))

然而,这给了我一个每年每个城市最大价值的数据集。但是,我只想知道比较所有城市一年的最大量。谢谢。

1 个答案:

答案 0 :(得分:1)

  library(dplyr)
  df %>%   #df is your dataframe
  group_by(year)%>%
  filter(volume==max(volume))

Source: local data frame [3 x 5]
Groups: year

     city sales volume year avg_price
1     nyc  2342 987651 2000      3127
2 abilene  3432  34342 2001      1234
3  kansas   123 999650 2002      2424


#updated : If you are grouping by both city and year

df %>%   #df is your dataframe
  group_by(year,city)%>%
  filter(volume==max(volume))

Source: local data frame [9 x 5]
Groups: year, city

     city sales volume year avg_price
1 abilene   239  12313 2000      7879
2  kansas  2324  18765 2000      2424
3     nyc  2342 987651 2000      3127
4 abilene  3432  34342 2001      1234
5     nyc  2342  10000 2001      3127
6  kansas   176   3130 2001       879
7  kansas   123 999650 2002      2424
8 abilene  3432  34342 2002      1234
9     nyc  2342  98000 2002      3127
相关问题