Independent Events in R

21 views
Skip to first unread message

Nia Smith

unread,
Aug 5, 2021, 9:34:22 AM8/5/21
to unmarked
Hi everyone,

I hope you are all doing well. Please forgive me for posting a slightly unrelated question in this group... I am not sure who else to ask..

I have a camera trap data set and wish to extract only the independent events for a given species (a event is considered independent if it is of the same species, at the same camera station, within a given time period e.g., 30 minutes). I can't get my code right. Does anyone on here perhaps have some R code they can share to work out 30 minute independent events?

Thank you in advance,

Best Wishes,
Nia

Nia Smith

unread,
Aug 5, 2021, 9:41:03 AM8/5/21
to unmarked
This is what I have so far, but it doesn't quite do what I wish for it to do...

The code below removes more records than it should. This is because the lag function only takes the record before the current one and does not take into account any events before that...

# Fake data:
df <- structure(
  list(
    spp = c("X", "X", "X", "X", "X", "X", "X", "X", "X", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Z", "Z", "Z", "Z", "Z", "Z", "Z"),
    loc = c(1, 1, 1, 1, 1, 1, 2, 3, 3, 1, 1, 2, 3, 3, 3, 4, 2, 3, 3, 3, 3, 3, 4),
    date_time = structure(c(1609451755, 1609452355, 1609581600, 1609582202, 1609583403, 1609585204, 1609668005, 1609538155, 1609841700, 1609495204, 1609583406, 1609668000, 1609539071, 1609756205, 1609758001, 1609581600, 1609668067, 1609451793, 1609452213, 1609452633, 1609495200, 1609626404, 1609581600), tzone = "", class = c("POSIXct", "POSIXt")),
    date = structure(c(18627, 18628, 18629, 18629, 18629, 18629, 18630, 18628, 18632, 18628, 18629, 18630, 18629, 18631, 18631, 18629, 18630, 18627, 18628, 18628, 18628, 18630, 18629), class = "Date"),
    time = c("23:55:55", "00:05:55", "12:00:00", "12:10:02", "12:30:03", "13:00:04", "12:00:05", "23:55:55", "12:15:00", "12:00:04", "12:30:06", "12:00:00", "00:11:11", "12:30:05", "13:00:01", "12:00:00", "12:01:07", "23:56:33", "00:03:33", "00:10:33", "12:00:00", "00:26:44", "12:00:00")),
  row.names = c(NA, -23L), class = "data.frame")

# Bad code:
df %>%
  arrange(date_time) %>%
  group_by(spp, loc) %>%
  filter(
    as.integer(
      difftime(date_time, lag(date_time), units = 'secs')
    ) > 1800 | row_number() == 1) %>%
  ungroup()

Thanks!   :)
Reply all
Reply to author
Forward
0 new messages