【问题标题】:How to compile the number of observations that follow a specific pattern?如何编译遵循特定模式的观察数量?
【发布时间】:2019-10-09 04:30:11
【问题描述】:

我有一个包含三个变量(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

示例:在给定的数据集中,单个 timediff

“单个时间差”= 44, 3 , 48

“双时间差”= 56, 1, 8, 40

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

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

感谢您的帮助!

【问题讨论】:

  • 你能澄清一下输出应该是什么样子吗?
  • @Dave2e 我不完全确定,但请参阅更新后的问题作为示例。

标签: r pattern-recognition


【解决方案1】:

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

【讨论】:

  • 知道为什么你会得到 8 个 timediff_1 和 1 个 timediff_2 吗?经过和物理计算,我分别得到 7 和 2。
  • 手动计算,你提供的样本数据我还是得到8和1。
  • 当我运行您的代码时,我收到一个错误,即找不到对象 n_timediff。我必须事先制作一个新对象吗?
  • 计数错误(., n_timediff):找不到对象'n_timediff'
  • 好吧,如果你的真实数据的结构与样本数据没有什么不同,那么我看不出你的问题的原因。不过,您可以尝试将dplyrtidyr 更新到最新版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
  • 1970-01-01
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多