当 Year Column 在 R 中包含多个年份时,如何找到包含最大值及其关联年份的行

How find the row containing the maximum value and its associated year, when the Year Column contains multiple years in R

当年份列包含多个年份时,如何找到包含最大值及其关联年份的行。我的数据框包含从 2013 年 1 月到 2020 年 12 月的每月河流流量数据。例如,如果我想找到包含 2013 年最大流量的行,或者我想找出 2013 年的最大流量和日期(date/month/year) 与那个特定的最大放电相关联。我该怎么做?在 R 中?

Year Discharge
1/1/2013 23
2/1/2013 45
- - --
12/31/2020 80

我们可以将列转换为日期 class,将 year 作为单独的列,按 slice max 行 [=23] 进行分组=]

library(dplyr)
library(lubridate)
df1 %>%
    group_by(year = year(mdy(Year))) %>%
    slice_max(n = 1, order_by = Discharge) %>%
    ungroup

-输出

# A tibble: 2 x 3
  Year       Discharge  year
  <chr>          <int> <dbl>
1 2/1/2013          45  2013
2 12/31/2020        80  2020

如果'Year'列中有多种格式,则使用parsedate

中的parse_date
library(parsedate)
df1 %>%
    group_by(year = year(parse_date(Year))) %>%
    slice_max(n = 1, order_by = Discharge) %>%
    ungroup

更新

根据评论中的 dput,'Date' 列已经在 Date class

df1 %>%
   group_by(year= year(Date)) %>%
   slice_max(n = 1, order_by = Discharge, with_ties = FALSE) %>%
    ungroup

-输出

# A tibble: 1 x 3
  Date       Discharge  year
  <date>         <dbl> <dbl>
1 2018-06-07    0.0116  2018

数据

df1 <- structure(list(Year = c("1/1/2013", "2/1/2013", "12/31/2020"), 
    Discharge = c(23L, 45L, 80L)), class = "data.frame", row.names = c(NA, 
-3L))