You could first group by year, then subset using the location of the maximum value of x per year using slice() and which.max().
library(dplyr)
library(clock)
set.seed(123)
# Example usage of `which.max()`
x <- c(1.5, 0.6, 3.3, 2.1)
# What location in `x` contains the max value?
which.max(x)
#> [1] 3
df <- tibble(
date = sort(as.Date("2017-01-01") + sample(1000)),
x = runif(1000) * 100
)
head(df)
#> # A tibble: 6 x 2
#> date x
#> <date> <dbl>
#> 1 2017-01-02 14.9
#> 2 2017-01-03 17.9
#> 3 2017-01-04 33.9
#> 4 2017-01-05 18.4
#> 5 2017-01-06 40.6
#> 6 2017-01-07 61.4
df %>%
mutate(year = get_year(date)) %>%
group_by(year) %>%
slice(which.max(x))
#> # A tibble: 3 x 3
#> # Groups: year [3]
#> date x year
#> <date> <dbl> <int>
#> 1 2017-04-21 100. 2017
#> 2 2018-10-18 99.8 2018
#> 3 2019-06-03 99.9 2019
Created on 2021-06-30 by the reprex package (v2.0.0)