Background: I have a data set of locations (with timestamp) from GPS collared bears which go in and out of a protected area. I can assign each location as being inside or outside the area already, but I'm looking for (ideally) a tidyverse solution to assign a unique ID to each "bout" of being outside the protected area, or to reshape the data such that each row is a bout, so that I can can generate summary statistics such as average duration outside park, etc.
Here is a reproducible example of the data (though it would have additional columns) I'm dealing with. Notice that the timestamp is duplicated across different bears. The first example shows a desired outcome with the data in "long" format, including a column "desired" with an identifier of bout. The second example shows roughly how the data might look in wide format, with the start and end times being the min() and max() times for each bout. I'd be happy to get either.
I'm new to tidyverse but I have to believe it offers a better way than doing this all manually in excel...
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#>
#> date
bears<-c("A","A","A","A","B","B","B","B")
stamp<-c("2010.09.30 08:00:00", "2010.09.30 10:00:00", "2010.09.30 12:00:00", "2010.09.30 14:00:00",
"2010.09.30 08:00:00", "2010.09.30 10:00:00", "2010.09.30 12:00:00", "2010.09.30 14:00:00")
state<-c("in","out","out","in","in","out","out","in")
desired<-c("1","2","2","3","4","5","5","6")
df<-as.data.frame(cbind(bears,stamp,state,desired))
df$stamp<-ymd_hms(df$stamp)
df
#> bears stamp state desired
#> 1 A 2010-09-30 08:00:00 in 1
#> 2 A 2010-09-30 10:00:00 out 2
#> 3 A 2010-09-30 12:00:00 out 2
#> 4 A 2010-09-30 14:00:00 in 3
#> 5 B 2010-09-30 08:00:00 in 4
#> 6 B 2010-09-30 10:00:00 out 5
#> 7 B 2010-09-30 12:00:00 out 5
#> 8 B 2010-09-30 14:00:00 in 6
bears2<-c("A","A","A")
stamp2<-c("start1","start2","start3")
stamp3<-c("end1","end2","end3")
state1<-c("in","out","in")
dfwide<-as.data.frame(cbind(bears2,stamp2,stamp3,state1))
dfwide
#> bears2 stamp2 stamp3 state1
#> 1 A start1 end1 in
#> 2 A start2 end2 out
#> 3 A start3 end3 in