Subsetting based on co-occurrence within a time window

谁说我不能喝 提交于 2019-12-01 01:43:40

Reproducing just your initial result with one A value, assuming your data is called dat, can be done like so:

with(dat,dat[
  (
    SP=="A" |
    Area==Area[SP=="A"]
  ) &
  abs(difftime(Time,Time[SP=="A"],units="mins")) <= 30,
]
)

Result:

   SP                Time Area
3   A 2013-09-09 09:22:00    1
5   D 2013-09-09 09:20:00    1
7   D 2013-09-09 09:03:00    1
9   F 2013-09-09 09:45:00    1
10  B 2013-09-09 09:15:00    1

To account for multiple occurrences of A, things get a touch more complex:

with(dat,dat[
  (
    SP=="A" |
    Area %in% Area[SP=="A"]
  ) & 
  apply(
    sapply(Time[SP=="A"],
    function(x) abs(difftime(Time,x,units="mins"))<=30 ),1,any
  )
,]
)

Though I'm sure there is probably a simplification possible here somewhere.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!