【问题标题】:How find the row containing the maximum value and its associated year, when the Year Column contains multiple years in R当年份列在 R 中包含多年时,如何找到包含最大值及其相关年份的行
【发布时间】:2021-11-18 00:00:08
【问题描述】:

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

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

【问题讨论】:

    标签: r select time-series max


    【解决方案1】:

    我们可以将列转换为 Date 类,将year 作为单独的列,将slicemax 行分组

    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
    

    如果“年份”列中有多种格式,请使用 parse_date 中的 parsedate

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

    更新

    根据 cmets 中的 dput,“日期”列已经在 Date 类中

    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))
    

    【讨论】:

    • 谢谢!我不确定它在计算什么,并且还收到如下警告消息:mutate()year 存在问题。我year = year(mdy(Year))。 i 所有格式都无法解析。未找到任何格式。
    • @SankarManalilkadaSasidharan 您的输入以月/日/年格式显示日期格式。你还有其他格式吗
    • @SankarManalilkadaSasidharan 尝试使用 parse_date 更新代码
    • 谢谢你,但它仍然给我错误。我想找到的只是包含最大排放值及其相关日期的行。我的年份列(例如格式 2013-01-01、2013-01-02、2013-01-03......直到 2020-12-31)包含几年。
    • @akrun 非常感谢您的帮助。代码正在运行,但有一个错字。我已经删除了 slice_max 前面的 %>%。非常感谢df1 %&gt;% group_by(year= year(Date)) %&gt;% slice_max(n = 1, order_by = Discharge, with_ties = FALSE) %&gt;% ungroup,我已经接受了你的解决方案!再次感谢您
    猜你喜欢
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多