Kyle Hand Kyle Hand - 1 month ago 10
R Question

Finding difference in dates by grouped variable

I am working on my Master's Thesis and need help with some R coding. I am analyzing movements of wild turkeys during different stages of reproduction. I need to find the difference in the last date and the first date that an individual was within an area.

x<- data.frame(
AreaID = c(1,1,1,1,2,2,2,2),
Timestamp=as.POSIXct(c("06/01/2014 05:01", "6/01/2014 13:00","06/01/2014 23:00", "06/02/2014 10:00","06/20/2015 09:00",
"06/20/2015 10:00", "06/20/2015 11:00", "06/20/2015 12:00"), format='%m/%d/%Y %H:%M'))


I need a new dataframe with AreaID and the time spent in that area.

Thanks for your help.

Answer Source
library(dplyr)
group_by(x, AreaID) %>%
    summarize(duration = max(Timestamp) - min(Timestamp))
# # A tibble: 2 x 2
#   AreaID      duration
#    <dbl>        <time>
# 1      1 1.207639 days
# 2      2 3.000000 days