Calculate Distance and Speed Between GPS Points #This code was written by Leonardo Custode. >>library(sf) >>library(parallel) >>library(foreach) >>library(stringr) >>directory <- "~/Desktop/Cat Stuff/Cat GPS Tracks/2019catcamshapefiles/" >> outdirectory <-"~/Desktop/Cat Stuff/Cat GPS Tracks/Speed output 2019 Shapefiles/" >> list <- list.files(directory,pattern = "\\.shp$",full.names = TRUE) #Creates a list of all shapefiles in the directory >> numCores <- detectCores() #detects the number of cores in the computer for multiprocessing >> registerDoParallel(numCores) #sets up dopar for multiprocessing >>foreach(i = 1:length(list))%dopar%{ #iterates through files equal to the number of cores in the computer simultaneously >>file <- st_read(list[i]) >>file$distance <- NA #creates a column called “distance which will store the distance from the last point in >>file$Timefrom <- NA # creates a column called “Timefrom” where the time elapsed between the last few points will be stored >>file$speed <- NA #This column stores the speed the cat would have had to travel to get between these two points >>for(j in 1:nrow(file)){ #iterates through each point in the shapefile >> if(isTRUE(j == 1)){next} #the first observation will not have previous observation so this skips it >>else if(isTRUE(j > 1)){ file[j,19] <- st_distance(file[j,],file[j-1,]) #calculates and stores the distance (m) between the current point and the previous point >> file[j,20] <-as.numeric(difftime(as.POSIXct(file[j,]$BeginTime), as.POSIXct(file[j-1,]$BeginTime),units = "secs")) #calculates and stores the time (s) between the current point and the previous point >>file[j,21] <- file[j,19]/file[j,20] #calculates and stores the speed the cat travelled between the current point and the previous point stored in m/s } } >>#TooFast <- 1.6667 #rewrite this variable to be the speed considered to be too fast for a cat to realistically travel >>#TooFar <- #set a distance that is considered to be too far for a cat to realistically travel >> #file <- file[file$speed < TooFast & distance > TooFar] >>fileout <- basename(list[i]) >>pathout <- str_c(outdirectory,fileout) >>file <- st_zm(file) >>st_write(file,pathout) #saves the new shapefile with distance, Timefrom, and speed }