如何编译遵循特定模式的观察数量?

How to compile the number of observations that follow a specific pattern?

我有一个包含三个变量(DateTime、Transmitter 和 timediff)的数据集。 timediff 列是发射器的后续检测之间的时间差。我想知道时间差异遵循特定模式的次数。这是我的数据示例。

> dput(Example)
structure(list(DateTime = structure(c(1501117802, 1501117805, 
1501117853, 1501117857, 1501117913, 1501117917, 1501186253, 1501186254, 
1501186363, 1501186365, 1501186541, 1501186542, 1501186550, 1501186590, 
1501186591, 1501186644, 1501186646, 1501186737, 1501186739, 1501187151
), class = c("POSIXct", "POSIXt"), tzone = "GMT"), Transmitter = c(30767L, 
30767L, 30767L, 30767L, 30767L, 30767L, 30767L, 30767L, 30767L, 
30767L, 30767L, 30767L, 30767L, 30767L, 30767L, 30767L, 30767L, 
30767L, 30767L, 30767L), timediff = c(44, 3, 48, 4, 56, 4, 50, 
1, 42, 2, 56, 1, 8, 40, 1, 53, 2, 37, 2, 42)), row.names = c(NA, 
20L), class = "data.frame")

所以看时间差列,我想知道有多少次有单个timediff < 8秒,有多少次有两次后续timediff < 8秒,有多少次有3次后续timediff < 8秒等。

示例:在给定的数据集中,单个时间差 <8 秒发生了 7 次,而两个后续时间差 <8 秒发生了两次。

A "single timediff" = 44, 3, 48

A "double timediff" = 56, 1, 8, 40

就输出而言,我会寻找这样的东西...

> dput(output)
structure(list(ID = 30767, Single = 7, Double = 2), class = "data.frame", row.names = c(NA, 
-1L))

感谢您的帮助!

一个 dplyr 可能性是:

df %>%
 mutate(cond = timediff <= 8) %>%
 group_by(rleid = with(rle(cond), rep(seq_along(lengths), lengths))) %>%
 add_count(rleid, name = "n_timediff") %>%
 filter(cond & row_number() == 1) %>%
 ungroup() %>%
 count(n_timediff)

n_timediff     n
       <int> <int>
1          1     8
2          2     1

考虑到 "Transmitter" 中可能有更多值,您可以这样做(这也需要 tidyr):

df %>%
 mutate(cond = timediff <= 8) %>%
 group_by(Transmitter, rleid = with(rle(cond), rep(seq_along(lengths), lengths))) %>%
 add_count(rleid, name = "n_timediff") %>%
 filter(cond & row_number() == 1) %>%
 ungroup() %>%
 group_by(Transmitter) %>%
 count(n_timediff) %>%
 mutate(n_timediff = paste("timediff", n_timediff, sep = "_")) %>%
 spread(n_timediff, n)

  Transmitter timediff_1 timediff_2
        <int>      <int>      <int>
1       30767          8          1