【问题标题】:Count number of rows for each row that meet a logical condition计算满足逻辑条件的每一行的行数
【发布时间】:2018-09-25 17:41:34
【问题描述】:

所以我有一些带有时间戳的数据,对于每一行,我想计算落在某个时间窗口内的行数。例如,如果我有以下数据,时间戳为 h:mm(列 ts),我想计算从该时间戳到过去五分钟发生的行数(列 count) .距离第一个数据点不到五分钟的前 n 行应该是 NA。

ts    data  count
1:01   123      NA
1:02   123      NA
1:03   123      NA
1:04   123      NA
1:06   123      5
1:07   123      5
1:10   123      3
1:11   123      4
1:12   123      4

使用 for 循环很简单,但我一直在尝试使用 apply() 系列来实现,但尚未发现任何成功。有什么建议吗?

【问题讨论】:

  • 所以我看到了如何修改固定时间窗口的答案(例如,OP 中从凌晨 2 点到凌晨 5 点),但不确定如何将其应用于相对/移动时间窗口,即时间 x + 5 分钟

标签: r apply


【解决方案1】:

编辑:修改以考虑每分钟多次读数的可能性,在评论中提出。

具有新的中间读数的数据:

library(dplyr)
df %>%
  # Take the text above and convert to datetime 
  mutate(ts = lubridate::ymd_hms(paste(Sys.Date(), ts))) %>%

  # Count how many observations per minute
  group_by(ts_min = lubridate::floor_date(ts, "1 minute")) %>%
  summarize(obs_per_min = sum(!is.na(data))) %>%

  # Add rows for any missing minutes, count as zero observations
  padr::pad(interval = "1 min") %>%
  replace_na(list(obs_per_min = 0)) %>%

  # Count cumulative observations, and calc how many in window that 
  #  begins 5 minutes ago and ends at end of current minute
  mutate(cuml_count = cumsum(obs_per_min),
         prior_cuml = lag(cuml_count) %>% tidyr::replace_na(0),
         in_window  = cuml_count - lag(prior_cuml, 5)) %>%

  # Exclude unneeded columns and rows
  select(-cuml_count, -prior_cuml) %>%
  filter(obs_per_min > 0)

输出(现在反映 1:06:30 的附加读数)

# A tibble: 12 x 3
    ts_min              obs_per_min in_window
<dttm>                    <dbl>     <dbl>
1 2018-09-26 01:01:00           1        NA
2 2018-09-26 01:02:00           1        NA
3 2018-09-26 01:03:00           1        NA
4 2018-09-26 01:04:00           1        NA
5 2018-09-26 01:06:00           2         6
6 2018-09-26 01:07:00           1         6
7 2018-09-26 01:10:00           1         4
8 2018-09-26 01:11:00           1         5
9 2018-09-26 01:12:00           1         4

【讨论】:

  • 所以我可以看到这对于在一分钟内发生的数据(即秒 = 0)非常有效,但是,如果在整分钟之间发生数据,它不会被低估,例如如果上面在01:06:30 处添加了一行,那么01:07:00in_window 将给出五,但正确的计数是六
猜你喜欢
  • 2021-08-13
  • 2013-10-14
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
  • 2021-02-05
相关资源
最近更新 更多