r - Finding difference in dates by grouped variable -


i working on master's thesis , need r coding. analyzing movements of wild turkeys during different stages of reproduction. need find difference in last date , first date individual within 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 new dataframe areaid , time spent in area.

thanks help.

the dplyr solution @gregor should work. however, if dplyr not functioning properly. can try approach using data.table.

library(data.table)  setdt(x) x[, .(duration = max(timestamp) - min(timestamp)), = areaid]    areaid      duration 1:      1 1.207639 days 2:      2 3.000000 days 

or use aggregate function base r.

aggregate(timestamp ~ areaid, data = x, fun = function(x) max(x) - min(x))   areaid timestamp 1      1 1.207639  2      2 3.000000 

update

to make unit of time consistent, can use difftime function units argument, "hours", "days" or other units.

aggregate(timestamp ~ areaid, data = x,            fun = function(x) difftime(max(x), min(x), units = "hours"))    areaid timestamp 1      1 28.98333  2      2  3.00000 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -