簡體   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