【问题标题】:Consecutive count by groups按组连续计数
【发布时间】:2016-12-21 02:03:38
【问题描述】:

如何按组生成条件累积计数?具体来说,我的数据有列:个人姓名、日期、月份和温度。我想生成一个表格,显示每个月内每个人温度超过 38oC 的连续天数。

一个答案解释了如何按组进行累积计数(如何在另一列有条件地按组执行列的连续计数),但我不确定如何添加我只想要累积计数的条件条件是温度大于 38oC。

原始表格如下所示:

Individual name | Month | Date   | Temperature
Greg            | 1     | 2/1/16 | 26
Greg            | 1     | 3/1/16 | 25
Greg            | 1     | 4/1/16 | 39
Greg            | 1     | 5/1/16 | 39
Fred            | 1     | 2/1/16 | 40
Fred            | 1     | 3/1/16 | 41
Fred            | 1     | 4/1/16 | 41
Fred            | 1     | 5/1/16 | 41

这是我想要生成的:

Individual name | Month | Largest consecutive string of days >38oC
Greg            | 1     | 2
Fred            | 1     | 4

【问题讨论】:

  • 另外,我意识到可能有多个连续天数>38oC(对于一个月内的个人),但我只需要知道满足此条件的最大连续天数。
  • 看看?by和?rle

标签: r count


【解决方案1】:

这是另一个不需要函数的 dplyr 选项

library(dplyr)
df1 %>%
  group_by(Individual_name, Month) %>%
  filter(Temperature>38 & lag(Temperature, n=1L)>38) %>%
  summarise(consecutive=n()+1)

【讨论】:

    【解决方案2】:

    这是一个使用data.table 的选项。将“data.frame”转换为“data.table”(setDT(df1)),按“Individual_name”、“Month”和逻辑向量的run-length-id(Temperature > 31)分组,我们得到sum逻辑向量,然后按 'Individual_name' 和 'Month' 分组,从前面的步骤中获取汇总列 ('V1') 的 max 值。

    library(data.table)
    setDT(df1)[, sum(Temperature > 31), .(Individual_name, Month, grp=rleid(Temperature > 31))
          ][, .(LargestConsec = max(V1)), .(Individual_name, Month)]
    #   Individual_name Month LargestConsec
    #1:            Greg     1             2
    #2:            Fred     1             4
    

    或者使用dplyr,我们通过基于“values”中的TRUE元素提取lengths来创建一个带有rle的函数(就像我们在逻辑向量上执行rle一样)。按“Individual_name”和“Month”分组,对“Temperature”应用函数以获取最大连续组的summarized 计数。

    f1 <- function(vec, thresh) {
        with(rle(vec > thresh), max(lengths[values]))
    }
    
    library(dplyr)
    df1 %>% 
        group_by(Individual_name, Month) %>% 
        summarise(LargestConsec = f1(Temperature, 31))
    #   Individual_name Month LargestConsec
    #            <chr> <int>         <int>
    #1            Fred     1             4
    #2            Greg     1             2
    

    数据

    df1 <- structure(list(Individual_name = c("Greg", "Greg", "Greg", "Greg", 
    "Fred", "Fred", "Fred", "Fred"), Month = c(1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L), Date = c("2/1/16", "3/1/16", "4/1/16", "5/1/16", 
    "2/1/16", "3/1/16", "4/1/16", "5/1/16"), Temperature = c(26L, 
    25L, 39L, 39L, 40L, 41L, 41L, 41L)), .Names = c("Individual_name", 
    "Month", "Date", "Temperature"), class = "data.frame", row.names = c(NA, 
    -8L))
    

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 1970-01-01
      • 2021-11-07
      • 2020-01-23
      • 2016-11-03
      • 1970-01-01
      • 2014-11-17
      • 2023-01-17
      • 1970-01-01
      相关资源
      最近更新 更多