Jojo
Jojo

Reputation: 5211

Split data when time intervals exceed a defined value

I have a data frame of GPS locations with a column of seconds. How can I split create a new column based on time-gaps? i.e. for this data.frame:

df <- data.frame(secs=c(1,2,3,4,5,6,7,10,11,12,13,14,20,21,22,23,24,28,29,31))

I would like to cut the data frame when there is a time gap between locations of 3 or more seconds seconds and create a new column entitled 'bouts' which gives a running tally of the number of sections to give a data frame looking like this:

id   secs bouts
1     1     1
2     2     1
3     3     1
4     4     1
5     5     1
6     6     1
7     7     1
8    10     2
9    11     2
10   12     2
11   13     2
12   14     2
13   20     3
14   21     3
15   22     3
16   23     3
17   24     3
18   28     4
19   29     4
20   31     4

Upvotes: 0

Views: 146

Answers (1)

Roland
Roland

Reputation: 132979

Use cumsum and diff:

df$bouts <- cumsum(c(1, diff(df$secs) >= 3))

Remember that logical values get coerced to numeric values 0/1 automatically and that diff output is always one element shorter than its input.

Upvotes: 4

Related Questions