【问题标题】:count the number of 3 consecutive days or more in R计算 R 中连续 3 天或更多天的数量
【发布时间】:2021-10-19 09:54:48
【问题描述】:

我想统计一年连续3天或以上的次数,给出连续天数,取这些连续天数和日期中的温度最大值

代码:

date = c("2018-07-26", "2018-07-27", "2018-07-31", "2018-08-03", "2018-08-04", "2018-08-05", "2018-08-06", "2018-08-07", "2019-06-25", "2019-06-26", "2019-06-27", "2019-06-28", "2019-06-29", "2019-06-30", "2019-07-01", "2019-07-05", "2019-07-22", "2019-07-23", "2019-07-24", "2019-07-25", "2019-07-26", "2020-07-21", "2020-07-30", "2020-07-31", "2020-08-01", "2020-08-09", "2020-08-10", "2020-08-11", "2020-08-21")
temperature_min = c(19.8, 21.1, 21.2, 22.0, 24.1, 26.0, 22.2, 25.0, 21.6, 20.4, 20.6, 24.8, 21.3, 24.7, 22.6, 19.6, 22.3, 21.2, 24.8, 24.6, 21.3, 21.5, 20.1, 22.3, 21.7, 19.4, 20.7, 20.6, 24.7)
temperature_max = c(34.7, 36.2, 34.6, 34.9, 36.7, 35.9, 35.8, 35.1, 35.1, 36.6, 38.1, 35.5, 37.6, 36.7, 35.3, 35.2, 34.6, 38.5, 39.7, 39.0, 36.7, 34.5, 37.2, 39.4, 36.4, 37.2, 36.8, 36.4, 35.7) 
data = as.data.frame(cbind(date, temperature_min, temperature_max ))

例如 2018 年连续 3 天(8 月 3 日至 7 日)有 1 次,即 5 天,且 temperature_max = 36.4(8 月 4 日)。 2019 年有 2 次连续 3 天(6 月 25 日至 7 月 1 日),即天数和 temperature_max = 38.1(6 月 27 日)和 5 天(8 月 22 日至 26 日),max = 39.7(8 月 24 日)。 2020 年也是连续 2 次 3 天(从 7 月 30 日到 8 月 1 日),即 3 天,temperature_max = 39.4(7 月 31 日)和 3 天(从 8 月 9 日到 11 日),max = 37.2(8 月 9 日)

所以我想要结果

【问题讨论】:

    标签: r


    【解决方案1】:

    这是一个可能的dplyr 解决方案-

    library(dplyr)
    
    data %>%
      mutate(date = as.Date(date),
             year = lubridate::year(date),
             group = cumsum(c(TRUE, diff(date) > 1))) %>%
      group_by(year, group) %>%
      filter(n() >= 3) %>%
      summarise(start = min(date), 
                duration = n(), 
                max = max(temperature_max), 
                date_of_max = date[which.max(temperature_max)], .groups = 'drop') %>%
      select(-group)
    
    #   year start      duration   max date_of_max
    #  <int> <date>        <int> <dbl> <date>     
    #1  2018 2018-08-03        5  36.7 2018-08-04 
    #2  2019 2019-06-25        7  38.1 2019-06-27 
    #3  2019 2019-07-22        5  39.7 2019-07-24 
    #4  2020 2020-07-30        3  39.4 2020-07-31 
    #5  2020 2020-08-09        3  37.2 2020-08-09 
    

    数据

    data = data.frame(date, temperature_min, temperature_max )
    

    【讨论】:

    • 很好用,非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2023-03-25
    • 2019-03-28
    • 2021-11-07
    • 2019-03-28
    相关资源
    最近更新 更多