The adehabitatLR::as.ltraj() function calculates animal trajectories. The function requires dates to be class POSIXct. I followed the same steps in the example section of the help document using a play dataset I found online and converted date-time to POSIXct dates but I still get the following error when running the function
Error in adehabitatLT::as.ltraj(xy = xy[id == "17", ], date = date[id == : For objects of type II, date should be of class "POSIXct"
Here is what I'm doing...
library(tidyverse)
library(lubridate)
library(rio)
library(sp)
library(adehabitatLT)
#import elk collar data
data<-import("https://www.sciencebase.gov/catalog/file/get/59d90ceee4b05fe04cc9b0f2?f=__disk__a8%2F84%2Fa6%2Fa884a68596e8ed85b6b956119db0f1fffc4e960c")
glimpse(data)
#following example: convert date-time to posixct, and ID to character
elk<-data%>%mutate(date=as.POSIXct(strptime(Date_Time_MST,"%m/%d/%Y",tz="US/Mountain")))%>%mutate(AID=as.character(AID))
#get id vector
id<-elk%>%dplyr::select(AID)
#get xy data
xy<-elk%>%dplyr::select(Easting, Northing)%>%coordinates()%>%as.data.frame()
#get dates
date<-elk%>%dplyr::select(date)%>%as.data.frame()
str(date)
#get trajectories for AID 17
tr<-adehabitatLT::as.ltraj(xy=xy[id=="17",],date=date[id=="17"], id="17")
Your date
object is not of class POSIXct
, it is a data.frame
. Don't mistake a frame with one column (that happens to be POSIXct
) equivalent for functions as a POSIXct
vector.
Also, I see no reason to break it out into individual vectors, that leaves room for inconsistent indexing, etc. I suggest something like this:
elk <- data %>%
mutate(date = as.POSIXct(Date_Time_MST, format = "%m/%d/%Y", tz ="US/Mountain"))) %>%
mutate(AID = as.character(AID))
tr <- with(elk[elk$AID == "17",],
as.ltraj(xy = coordinates(cbind(Easting, Northing), date = date, id = AID))
If you're going to be doing this one-call for multiple id
s (or even all of them) in elk
and want to automate it, you can generate a list-column (saved for later use) with something like:
elk_with_tr <- elk %>%
filter(id %in% c("17", ...)) %>% # some other IDs of interest to you
mutate(
tr = Map(as.ltraj, xy=coordinates(cbind(Easting, Northing)), date=date, id=AID)
)
and this new frame will have a list
-column named tr
with all of the results.