繁体   English   中英

计算符合逻辑条件的每一行的行数

[英]Count number of rows for each row that meet a logical condition

因此,我有一些带有时间戳的数据,并且对于每一行,我想计算在特定时间范围内的行数。 例如,如果下面的数据带有一个以h:mm为时间戳的数据(列ts ),我想计算从该时间戳到过去五分钟的行count (列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()系列实现,但尚未获得任何成功。 有什么建议么?

编辑:修改为考虑到每分钟可能出现多次读数的可能性,并在注释中提出。

具有新的分钟中读数的数据:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM