date of of annual maxium

Hi all,

I have a daily time series of two variables and i want to get the annual maxumum for each variable with the actual date. i tried using apply.yearly(x$Prcp, max) but this only gives the maximum values with the last date of the year as

1979-12-31 34.72
1980-12-31 47.02
1981-12-31 33.68
1982-12-31 25.22
1983-12-31 32.13
...........
2019-12-31 120

for example for 1979, the annual maxum is on 07/05/1979.

is there any way to extract the maxum and its excate date?

Best regards,

Solomon

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)

Thank you davis. it did work

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.