luciano
luciano

Reputation: 13852

Find highest value in decade

I have this data frame in 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
..   ...  ...

How can I find the highest count in each decade (70s...10s)?

Upvotes: 1

Views: 117

Answers (2)

gwatson
gwatson

Reputation: 488

Using dplyr:

library(dplyr)

df %>% group_by(floor(year/10)*10) %>% summarise(max_cnt = max(count))

Upvotes: 5

joran
joran

Reputation: 173737

Another option, since you're already using dplyr

df %>%
    mutate(decade = floor(year / 10) * 10) %>%
    group_by(decade) %>%
    top_n(n = 1,wt = count)

Upvotes: 4

Related Questions