我在R中有这个数据框:
set.seed(1)
count <- sample(1:100, 100, replace = TRUE)
set.seed(2)
year <- sample(1970:2015, 100, replace = TRUE)
library(dplyr)
df <- data_frame(count, year)
df
Source: local data frame [100 x 2]
count year
1 27 1978
2 38 2002
3 58 1996
4 91 1977
5 21 2013
6 90 2013
7 95 1975
8 67 2008
9 63 1991
10 7 1995
.. ... ...
我怎样才能找到每十年(70s ... 10s)的最高数量?
答案 0 :(得分:5)
使用dplyr:
library(dplyr)
df %>% group_by(floor(year/10)*10) %>% summarise(max_cnt = max(count))
答案 1 :(得分:4)
另一种选择,因为您已经在使用 dplyr
df %>%
mutate(decade = floor(year / 10) * 10) %>%
group_by(decade) %>%
top_n(n = 1,wt = count)