by john leonard - ckwri.tamuk.edu...are often overly broad, tending to inundate the user with...
TRANSCRIPT
ANALYZINGWILDLIFETELEMETRYDATAINR
ByJohnLeonard
2
TABLEOFCONTENTSINTRODUCTION……………………………………………………………………………………………………………………………………….3USINGRSTUDIO……………………………………………………………………………………………………………………………………….4INSTALLINGRANDRSTUDIO……………………………………………………………………………………………………………………5INSTALLINGANDLOADINGREQUIREDPACKAGES……………………………………………………………………………………7LOADINGRCODEINTORSTUDIO…………………………………………………………………………………………………………….7FORMATTINGINPUTLOCATIONDATA…………………………………………………………………………………………………….8CREATINGALISTOFSPATIALPOINTSDATAFRAMES……………………………………………………………………………….9PLOTPOINTSTOREMOVEOUTLIERS……………………………………………………………………………………………………..13REPROJECTINGPOINTS………………………………………………………………………………………………………………………….16EXPORTINGPOINTSASSHAPEFILES……………………………………………………………………………………………………….17MAKINGMINIMUMCONVEXPOLYGONHOMERANGES………………………………………………………………………..18MAKINGKERNELHOMERANGESINADEHABITATHR……………………………………………………………………………..20MAKINGKERNELHOMERANGESINRHR……………………………………………………………………………………………….25ADDINGFIELDSTOGPSLOCATIONSFILES……………………………………………………………………………………………..27BROWNIANBRIDGEMOVEMENTMODELS…………………………………………………………………………………………….29FINDINGCODESFORCOORDINATEREFERENCESYSTEMS……………………………………………………………………..35SPECIFYINGDATEANDTIMEFORMAT…………………………………………………………………………………………………..37TROUBLESHOOTING………………………………………………………………………………………………………………………………38APPENDIXA……………………………………………………………………………………………………………………………………………40InstallRequiredPackages………………………………………………………………………………………………………………………40CreateListofSpatialPointsDataFrames………………………………………………………………………………………………41PlotPointstoRemoveOutliers………………………………………………………………………………………………………………43Re-projectPointstoUTM………………………………………………………………………………………………………………………44ExportPoints…………………………………………………………………………………………………………………………………………45CreateMCP……………………………………………………………………………………………………………………………………………46CreateKDEadehabitatHR………………………………………………………………………………………………………………………47CreateKDErhr……………………………………………………………………………………………………………………………………….48CreateNewFields………………………………………………………………………………………………………………………………….49CreateBBMM………………………………………………………………………………………………………………………………………..51APPENDIXB……………………………………………………………………………………………………………………………………………53GPS_A……………………………………………………………………………………………………………………………………………………53GPS_B……………………………………………………………………………………………………………………………………………………54GPS_C……………………………………………………………………………………………………………………………………………………55GPS_D……………………………………………………………………………………………………………………………………………………56GPS_E…………………………………………………………………………………………………………………………………………………….57
3
INTRODUCTION
Rhasbecomethedominantplatformfordatamanipulationandanalysisinwildlifescience,yet
ithasareputationamongwildlifescientistsasbeingcounterintuitiveanddifficulttouse.Therearea
numberofintroductoryRmanualsavailable,butstrangely,veryfewpeopleseemtobeabletolearnto
codeinRbyreadingthesemanuals.ResourcesavailableforlearningRtendtofallintotwocategories.
Thefirstcategoryconsistsofbasicintroductorytextswithnameslike“IntroductiontoR”and“Rfor
Dummies”.ThesebooksattempttogivebeginnersanoverviewofallthefunctionalitiesofR,yetthey
areoftenoverlybroad,tendingtoinundatetheuserwithunnecessaryinformationandgivinglittlein
thewayofimmediatelyusefultechniques.Afterreadingoneofthesetextsfewpeopleareableto
immediatelystartusingRtoanalyzetheirowndata.
Attheotherendofthespectrumarevignettesdevelopedforspecificpackagesrelevantto
wildlifescientists,suchas“adehabitatHR”.Inmyopinion,workingthroughthesevignettes,complete
withsampledata,isabetteruseoftimethanreadingthe“IntroductiontoR”books.However,these
vignettestendtohavesomemajorshortcomings.Forone,thesampledataisalmostalwaysformatted
insomestructurethatmakesitworkseamlesslywiththepackage’sfunctions,andlittleinformationis
typicallyprovidedabouthowtoputone’srawdatainthecorrectformat.Additionally,thepackage
vignettestypicallyassumethattheuserwantstoconductallanalysesinR,ratherthanuseaGIS
programsuchasArcGIStoviewshapefilesandproducethefinalmaps.Inmyexperience,mostpeople
wouldliketolearntouseRtoautomatetediousandtimeconsumingtasks,butstillplantouseArcGIS
formakingvisually-appealingrepresentationsoftheirdata.
Thismanualfallssomewherein-betweentheintroductorytextsandpackagevignettes.It
describesaworkflowformanipulatingandprocessinglargeamountsofanimallocationdataobtained
fromGPSorVHFradiocollars.Itusesexistingpackagestoperformoperationssuchashomerange
estimation,butitallowsthesefunctionstobeappliedtoalargenumberoffilesquicklyandefficiently.
4
Assuch,thecodeprovidedinthismanualdoesnotconstituteapackage,butratheranintegrated
workflowforusingexistingpackages.Mygoalwastowriteamanualthatallowsaresearcherwithno
previousexperiencecodinginRtoperformallfunctionsdescribedinthismanualonhisorherdatasets.
Ithereforetriedtoleavenothingoutofthismanual,describingtheentireworkflowfrommodifyingthe
originaltelemetryfilestoexportingshapefiles.ForsomeonecomfortablewithRthiswillprobablybe
overkill,butforafirsttimeuserIbelievethislevelofdetailisessential.
Inmyexperience,thebestwaytolearntouseRistoimmediatelystartanalyzingyourowndata.
Ifyouknowafewbasicfunctionsthatareactuallyusefulandproducemeaningfulresultsyouwillbe
wellonyourwaytomakingRworkforyou.Withthatinmind,thismanualdescribesarelativelylimited
numberofoperationsanddoesnotgointogreatdetailexplaininghowRworks.
Myintentionisforthismanualtobeastand-alonedocument,meaningthatlinkstoadditional
filesarenotnecessary.InsteadofprovidinglinkstofilescontainingtheRcode,allcodedescribedinthis
documentcanbefoundinAppendixA.Someverysimplesampledatafilesareprovidedasplaintextin
AppendixB.ThisisaratherunconventionalapproachtoprovidingexampledataandRcode,butithas
theadvantageofprovidingtheuserwitheverythingheorsheneedstoanalyzewildlifetelemetrydata
inasingledocument.MyrecommendationistofirstusethesampledataprovidedinAppendixBto
workthroughtheentireworkflowdescribedinthismanual,andthentorepeattheprocessusingone’s
owndata.
USINGRSTUDIO
MostintroductoryRbooksstronglysuggestusingRStudio,butIconsideritsusemandatory.Itis
counterproductivetotrytolearnRjustusingthebaseRGUI.RStudioprovidestoolsforediting
commandsbeforeexecutingtheminR,letstheuserviewplotswithouthavingtosavethem,and
displaysallobjectsthatarepresentintheworkingenvironment.RStudioprovidesaneasywaytoaccess
5
anduseR,soitonlyworksifyouhaveRinstalled.SeeFigure1forasimplekeytothedifferentpartsof
theRStudiointerface.
INSTALLINGRANDRSTUDIO
ToinstallR,gotohttps://www.r-project.organdfollowtheinstructionsforinstallingthelatest
versionofR.ToinstallRStudiogotohttps://www.rstudio.com/products/rstudio/download/andfollow
theinstructionstoinstallthelatestversionofRStudio.Thesestepsareprettyself-explanatory,andI
haveneverrunintoanyproblemswiththis.Riscontinuouslyupdated,anditisprobablyagoodideato
alwayshavethemostup-to-dateversionofRinstalled.IfyoualreadyhaveanearlierversionofR
installedandwouldliketoupdateit,theeasiestwaytodothisistocopyandpastethefollowingcode
directlyintotheRGUI(notRStudio).
# installing/loading the package: if(!require(installr)) { install.packages("installr"); require(installr)} #load / install+load installr # using the package: updateR() # this will start the updating process of your R installation. It will check for newer versions, and if one is available, will guide you through the decisions you'd need to make.
6
Figure1:ScreencaptureofRStudiointerfacewithsomedataloaded.
A)Sourcebrowsernotebook-YoucanopenandeditRscriptsinthiswindow.Nothinghappensifyouclick“enter”onalineinthiswindow,though.Youhavetoeitheruse“ctrl+enter”orclick“Run”toactuallysendacommandtotheConsolewherethecommandiscarriedout.Youcanalsoviewdataframes,matricesandotherobjectsinthiswindow.B)Environmenttab-Thisshowsalltheobjectspresentinyourworkingenvironment.Clickingonthe“History”tabwillshowahistoryofeverythingyoutypedintotheconsole.Forvirtuallyanyproject,youwillbecreatingalargenumberofobjects.Havinganenvironmenttabthatshowsyoualltheobjectsthathavebeencreatedisextremelyuseful.C)Packagestab-Thistabshowsallthepackagesthathavebeeninstalled.Toloadaparticularpackage,clickontheopenboxbythepackagename.Theothertabsinthiswindoware“Files”,“Plots”,“Help”and“Viewer”.The“Files”browsershowsthefilesandsubdirectoriesofagivendirectory.The“Plots”tabwillletyouscrollthroughanyplotsorimagesyoucreated.The“Help”tabwillshowyouthedocumentationformostfunctionsorpackagesyouwillbeusing.The“Viewer”tabisusedtoviewlocalwebcontent.D)TheRConsole-Thisiswherethingsactuallyhappen.Thisiswhereyouwillrunscripts,executefunctions,andgeterrormessages.Whenyoudecidetorunsomecodethatyoutypedupintab“A”itwillbesentdowntotab“D”-theRconsole.IfyouusethebaseRGUIthisRConsoletabisprettymuchallyouget.
7
INSTALLINGANDLOADINGREQUIREDPACKAGES
PackagesarecollectionsoffunctionsandcompiledRcodethatbuilduponandexpandthebase
functionsofR.InordertouseapackageyoumustfirstinstallthepackageandthenloaditintoyourR
workingenvironment.Thefollowingpackagesarerequiredtoworkthroughthismanual:“sp”,
“lubridate”,“rgdal”,“maptools”,“adehabitatHR”,“rgdal”,“raster”,“BBMM”,“lunar”,“oce”,and“rhr”.
ThefirstcodeblockprovidedinAppendixAshouldinstallallpackagestoalocallibraryandloadthem
intotheRworkingenvironment.Usually,everythingwillworkifyoujusthighlighttheentirecodeblock
andrunitinRStudio.YoucancheckwhichRpackageshavebeeninstalledbyclickingonthe“Packages”
tabinRStudio.Thiswillopenupalistofavailablepackageswithopenboxeslocatedtotheleftofeach
box.Clickingontheboxtofillitinwithacheckmarkwillloadthatpackageintotheworking
environment.Ifsomeoftherequiredpackagesfailtoloadyoucanmanuallyloadthembyclickingon
theopenboxes.IfoneormorepackagesdidnotinstallyoucanmanuallyinstallitthroughRStudioby
clickingonTools>InstallPackages,andtypinginthenameofthepackage.Thiswillworkforallpackages
except“rhr”whichmustbeinstalledusingthecodeprovidedinthefirstcodeblockofAppendixA.I
recommendmakingsurethatallrequiredpackagesareinstalledandloadedbeforetryingtouseanyof
theothercodeblocks.Ineachcodeblock,Iincludedafewlinestomakesuretherequiredpackagesfor
thatcodeblockwereinstalled,butitisstillprobablybesttoensureallpackagesareinstalledandloaded
attheverybeginning.
LOADINGRCODEINTORSTUDIO
TheworkflowIcreatedforanalyzingandmanipulatingGPScollardataissavedas10different
textfileswhichcanbethoughtofas“codeblocks”.Eventhoughthisworkflowisintendedtomove
seamlesslythroughthesecodeblocks,IdecidedtokeeptheseseparateasIbelievethiskeepsthings
neatandeasiertouseinRStudio.All10codeblocksaresavedinAppendixAofthismanual.
8
ToloadthesecodeblocksintoRStudiofirstgotoFile>NewFile>RScript.Thiswillopenupa
blankpageintheSourcebrowsernotebookofRStudio.Next,highlightoneofthecodeblockstocopy
andpasteitintothisblankpage.Repeattheprocessforallcodeblocks,givingeachcodeblockitsown
tab.Youcantheneasilymovefromonecodeblocktoanotherbyselectingthecorrecttab.
Torunthecodeinanyoneofthesecodeblocks,simplyhighlighttheentirepage(aftercorrectly
modifyinganyuserdefinedinput)andclick“Run”atthetopoftheSourcebrowsernotebook.Thiswill
sendthecodetotheRConsoleandexecutethefunctions.Asmentionedintheintroduction,thereare
noadditionalfilesthatneedtobedownloadedtousethismanual.Allfunctionsdescribedinthis
documentareprovidedasblocksofplaintextinAppendixA.
FORMATTINGINPUTLOCATIONDATA
TheRcodedescribedinthismanualisintendedtosavetimebyautomatingmanyofthe
operationspeopleperformonanimallocationfiles.Forthistowork,allfilesmustbesavedascomma
delimitedcsvfilesandplacedinthesamefilefolder.Theprojectionanddatumusedshouldbeidentical
forallfiles,andthecolumnheadingsspecifyingxandycoordinates,andanydateandtimefields,should
bethesame.Anyweirdformatting,suchasskippedrowsorsingleheadingscoveringmultiplecolumns,
shouldberemoved.Columnheadingsshouldnotcontainspacesandshouldnotbeginwithanumber.
AneasywaytoformatinputfilesistoopeneachoneinExcel,deleteanyextraneouscolumnsorrows,
modifycolumnheadingsasneeded,andresavethefileasacsvfile(Fig.2).
Youcanuseyourownanimaltelemetrydataastheinputforthesefunctions,oryoucanusethe
sampledatainAppendixB.AppendixBcontains6simplifiedcomma-delimitedfileswithanimalGPS
data.Thesamplefilesnamed“GPS_A”,“GPS_B”,and“GPS_C”containGPSlocationscollectedfar
enoughaparttemporallytobeconsideredindependent.Thesefilesshouldbeusedforanyfunctions
involvingkernelorminimumconvexpolygon(MCP)homerangeestimation.Thesamplefilesnamed
9
“GPS_D”and“GPS_E”containlocationpointscollectedat30-minuteintervalsandthereforearehighly
auto-correlated.TheseshouldbeusedforanyfunctionsinvolvingBrownianbridges.Tousethesample
data,highlightitandpasteitintoatexteditorsuchasNotepad.Thensaveitwitha“.csv”extension
(e.g.,“GPS_A.csv”).Placeallofthesecsvfilesintoafilefoldercontainingnootherfiles.
Figure2:ExampleofrawGPScollardatathatneedstobemodified.Rows2and3shouldbedeleted.Anycolumnheadingswithaspaceinthem(e.g.“GMTDate”)shouldbechangedtosomethingwithnospace(e.g.,“GMT.Date”).Theentirefilethenneedstobesavedasacomma-delimitedcsvfile.CREATINGALISTOFSPATIALPOINTSDATAFRAMES
ASpatialPointsDataFrameisaspecialclassofRobjectthatcanbecreatedusingthepackage
“sp”.Ataminimum,aSpatialPointsDataFramewillcontaindefinedxandycoordinates.TheSpatial
PointsDataFramedoesnotnecessarilyneedtocontainprojectioninformation,butallsubsequent
analyseswillbeeasierifwedospecifyprojectioninformation.SpatialPointsDataFramesdifferfrom
10
“SpatialPoints”objectsinthattheformerallowstheinclusionofanynumberofnon-spatialattributes.
ThisisconvenientifwewanttolatersubsetlocationdatabasedonattributessuchasHDOP,numberof
satellites,ortimeofday.
AlististhemostgeneraltypeofdatastructureinR,anditbasicallyconsistsofanynumberof
dataobjects,ofsimilarordifferentclasses,groupedtogetherinaspecificorder.Aneasywayto
automatefunctionsinRistotellRtoapplyaspecificsetofcommandstoeachobjectinalist.Iliketo
thinkofthisascreatinganassemblylinewithyourdata,andthentrainingamachinetoperformspecific
operationsoneachobjectthatispasseddowntheassemblyline.
OncetheinputGPSfilesareformattedcorrectly,loadthecodeblocktitled“CreateListofSpatial
PointsDataFrames”intothesourcebrowsernotebookinRStudio.ThefirstseverallinesofthisRfilewill
appearasbelow:
# Create List of Spatial Points Data Frames # Animal locations must be saved as separate csv files in a single folder # Column headings for x and y coordinates and Date and Time fields must be identical # Created by John Leonard 08_23_2016 # User defined input. Modify lines below. ############################################################################# input = "J:/R/R for GPS collar data/Test Collar Data" x = "Longitude" # The column name of your x coordinate y = "Latitude" # The column name of your y coordinate datetime.code = "dmy_HMS" #modify this using documentation in Lubridate Datecolumn= "GMT.Date" Timecolumn= "GMT.Time" timezone = "UTC" input.projection = "+init=epsg:4326" #############################################################################
Thecodefallingbetweenthelinesofhashtags(#)isconsidered“userdefinedinput”andwill
needtobemodified.Anythingwithinquotationmarkscanbechangedtoreflectthefilefolderlocation,
columnheadings,andformatofyourdata.Anytextappearingafterthehashtagsisonlyforexplanation
purposesandwillnotactuallyberun.Themeaningsofthevariousfieldsareprovidedbelow:
11
“input”referstothecompletefilepathwaywhereyourGPSlocationsfilesarestored.Itis
importanttonotethatforwardslashesareusedinsteadofbackslashestoseparatefilefolders.Also,if
youarestoringyourdataonanexternalhard-driveandusingdifferentcomputerseachtime,thefullfile
pathwaymaybedifferenteachtime.Forexample,dependingonwhichcomputerandUSBportIuse,
thefilepathwayformydatawillusuallyeitherstartwitha“J”oran“F”.Makesurethatyouhave
permissiontomodifythefilefolderspecified.Forexample,youmightneedadministratorprivilegesto
writefilesdirectlytotheCdriveofaUniversitycomputer.
“x”isthecolumnnameforthexcoordinate.SpellthisoutexactlyasitappearsinyourGPSdata
files.
“y”isthecolumnnamefortheycoordinate.SpellthisoutexactlyasitappearsinyourGPSdata
files.
“datetime.code”isacodethatspecifiestheorderinwhichday,month,year,hour,minute,and
secondwillappearinyourcombined“Date_Time”column.“dmy_HMS”means:day,month,year,
(space),hour,minute,second.Seedocumentationforthepackage“lubridate”formoredetails.
“timezone”–tofilloutthisfieldyouneedtoknowthecorrecttimezonecodeforyourdata.
“UTC”isCoordinatedUniversalTimewhichisthetimezoneformerlyknownasGreenwichMeanTime
(GMT).See“lubridate”documentationformoredetails.
“input.projection”-thisisthemostdifficultfieldtofilloutcorrectly.Itspecifiesthecoordinate
referencesystemofyourxandyfields.ThecodedisplayedabovespecifiesLatitude/Longitudewith
decimaldegrees.
ThenextstepistohighlighttheentirepageofcodeandclickRun.Thismaytakeafewminutes
dependingonhowmanydifferentGPSdatafilesyouhave.Ifallgoeswell,theEnvironmenttab(usually
tothefarright)inRStudiowillbepopulatedwithseveralnewobjects(Fig.3).
12
Figure3:EnvironmenttabinR-studioafterimportingGPSlocationsfilesandcreatinglistofSpatialPointsDataFrames.
Theoneobjectwecareaboutis“newlist”whichisourlistofSpatialPointsDataFrames.Wecan
clickonthebluearrowtotheleftof“newlist”inourEnvironmenttabtoseewhatisinsidethisobject
(Fig.4).Formyparticulardataset,thenewlistobjectcontains3SpatialPointsDataFrames,each
correspondingtooneof3individuals.Allattributesoriginallypresentinmydataarelistedunderthe
“@data”slot.ItisworthspendingabitoftimelookingatthecontentsofnewlistinR-studio.Noticethat
someoftheattributesarecodedasFactorclasses,whereasothersarecodedasintegerornumerical.
TheDate.TimefieldthatwecreatedisclassPOSIXct,whichpertainsspecificallytodate/timefields.
ScrollingdownundertheEnvironmenttabrevealsseveralotherslots,including“@coords”,
whichcontainsourcoordinateinformation,and“@proj4string”,whichcontainsprojectioninformation.
13
Figure4:ViewingstructureofnewlistintheRStudioEnvironmenttab.
PLOTPOINTSTOREMOVEOUTLIERS
Wearenowreadytoplotpointsandremoveanyoutliersthatmaymessupouranalysis.Before
deployingGPScollars,itiscommonforresearcherstoturntheGPScollarontoacquireafewfixes.This
usuallyresultsinaGPSlocationsfilethatcontainssomeerroneouspoints.Theseareusuallyprettyeasy
tospotastheyareoftenlocatedfarfromtheanimal’sactualhomerange.Youcanalwaysremovethese
pointsinExcelwhileyouareformattingyourGPSlocationsfiles,oryoucandoitlaterinR.Evenifyou
doremoveerroneouspointsearlyoninExcel,itisstillagoodideatoplotpointstomakesure
everythinglookscorrectbeforetryingtogeneratehomeranges.
Loadthecodeblocknamed“PlotPointstoRemoveOutliers”intheRStudioSourcebrowser
notebooktab.Thiscodeusesthe“newlist”objectyoucreatedearlierasinput.Toplotthepointsyou
justneedtorunthefollowing3linesofcode:
for (i in 1:length(newlist)){ plot(newlist[[i]]@coords, main=names(newlist[i])) }
14
ThiswillproduceauniqueplotofpointsforeachGPSlocationsfile.Thefilenamewillbe
displayedastheplottitleandthexandycoordinateswillbedisplayedonthexandyaxes(Fig.5).
Figure5:Exampleplotcreatedusingcodeblockentitled“Plotpointstoremoveoutliers”.
FromtheexampledisplayedinFig.5youcanseeatleast1pointthatprobablyshouldn’tbe
there.ThepointlocatedatthefarupperleftoftheplotprobablyresultedfromtestingtheGPScollarat
home.YoucouldgointoExcelandtrytoindividuallyremovethesepoints,oryoucouldautomatethis
processusingR.
Ifyouarecarryingoutanyfunctionsthathavethepotentialtopermanentlyalteryourdataitis
agoodpracticetofirstmakeacopyofthedata.Wewillcreateacopyofnewlistcalled“newlist2”.We
willrunsomefunctionsintendedtoremoveoutliersfromnewlist2andthenplottheresultstomake
15
sureitworked.Notethatallcodebelowline8in“Plotpointstoremoveoutliers”needstobemodified
foryourparticulardataset.
TherearealotofwaystomodifyindividualSpatialPointsDataFrameswithinnewlist,butthe
exampleincludedintheRfile“Plotpointstoremoveoutliers”usestherangeofLatitudeandLongitude
valuestoaccomplishthis.Forthesampledata,GPS_A(Fig.5),wecanseethatallbutoneofthepoints
arelocatedinthebottomrightcornerofthegraph.Wecansubsetthisfiletoincludeonlypointswith
Latitude(ycoordinate)below27.Thiswilleffectivelyremovetheoutlierpointintheupperleftcornerof
thegraph.ForGPS_B(notshown)weinsteadsetaminimumvalueforLongitude(xcoordinate).
# First make duplicate of newlist called newlist2 just to be safe newlist2<-newlist # Modify code below to select maximum or minimum x or y values # Code below makes "27" the maximum latitude value for GPS_A newlist2$GPS_A<-subset(newlist2$GPS_A, newlist2$GPS_A@coords[,y]<27)
Theabovecodecanbemodifiedtofityourdataset.Thefieldsafterthe“$”(e.g.GPS_A,
GPS_B)shouldbechangedtothenamesofwhicheverlocationsfilesyouwanttoworkwith.Ifyouwant
tosubsetpointsbasedonLatitudeyoushouldstilluse“@coords[,y]”,butspecifywhichever
minimumormaximumvalueisappropriateforyourdata.Afteryouthinkyouhaveremovedtheoutliers
fromeachSpatialPointsDataFrameinyournewlistobject,plotthepointsagain(Fig.6).
16
Figure6:PlotofpointsforGPS_Aafteroutlierpointhasbeenremoved.
Ifeverythinglooksgood,youcanconvertnewlist2backintonewlistwiththefollowingcode:newlist<-newlist2
Youshouldbecarefulwiththeabovestep,asyoucannotundoit.Ifyouwanttomodifythe
codein“Plotpointstoremoveoutliers”toperformmorecomplexsubsettingoperations,suchas
removinglocationswithhighHDOP,youmaywanttoskiptheabovestepandinsteadmodifyall
followingcodeblocksbyreplacing“newlist”with“newlist2”.
REPROJECTINGPOINTS
ThecodetogenerateMCPandkernelhomerangeestimateswillworkfineregardlessofthe
coordinatesystemusedforyourinputpoints.Shapefileswillbegeneratedwiththeappropriate
projectionandtheywillthereforeappearinthecorrectlocationswhenyouopentheminArcGIS.
However,thesecodeblocksalsoautomaticallycalculatehomerangearea(ha.)andoutputthis
17
informationtoamatrix.Inordertodothiscorrectly,theunitsofthexandycoordinatesmustbein
meters.TheeasiestwaytoaccomplishthisistochangethecoordinatesystemofthedatatoUTMusing
thecodeblock“Re-projectPointstoUTM”.
Afterexecutingthiscode,“newlist”willcontainSpatialPointsDataFrameswithxandy
coordinatestransformedtothedesiredprojectionanddatum(e.g.,UTMNAD83).Ifyourlocationsfiles
arealreadygivenasUTMcoordinatesyoucanskipthisstepentirely.Aslongasyouspecifythecorrect
projectioninthe“CreateListofSpatialPointsDataFrames”steptheywillbeprojectedcorrectly.
EXPORTINGPOINTSASSHAPEFILES
ImportingtextfilesintoArcGISmanuallyandthenconvertingtheseintoshapefilesisn’t
particularlydifficult,butitistimeconsuming.Ifyouhavealotoftelemetryfilesyoucanautomatethe
processbyhavingRloopthrougheachSpatialPointsDataFramein“newlist”andwriteashapefilefor
eachone.Todothis,loadthecodeblocktitled“ExportPoints”intotheRStudioSourcenotebook
browserandsimplyhighlightandrunallcode.Theshapefileswillbewrittentoyourworkingdirectory
anda“.prj”filespecifyingprojectioninformationwillbegiven.Theprojectionwillbewhateveryoure-
projectedyourpointsto.Ifsomeofyourcolumnsareformattedasunusualclasses(e.g.,POSIXct)they
mightnotimportintoArcGIScorrectly.Topreventthisfrombeingaproblem,convertanycolumnswith
questionableclassestocharacterfields.ThishasalreadybeendoneforthePOSIXctfieldcalled
“Date.Time”withthefollowingcode:
infile$Date.Time<-as.character(infile$Date.Time) WhenyouopenthenewpointsshapefilesinArcGIStheywillbeprojectedinwhatever
coordinatesystemyouselectedinthepreviousstep.However,thedefaultnamesgiventothexandy
coordinateswillnotbecorrect.IfyouroriginalpointswereinLatitude/Longitudeandyouchangedthem
18
toUTM,thepointswillshowupinthecorrectlocationinArcGIS,buttheattributetablewillread
Longitude_1,andLatitude_1forUTMxandycoordinatesrespectively.
MAKINGMINIMUMCONVEXPOLYGONHOMERANGES
IfalloutlierpointshavebeenremovedfromeachoftheSpatialPointsDataFramesinside
“newlist”,wearereadytogeneratehomerangeestimates.Minimumconvexpolygons(MCPs)are
amongthesimplesthomerangeestimatorssowewillstartwiththose.LoadtheRfilecalled“Create
MCP”intotheSourcebrowsernotebook.TheonlyuserdefinedinputforthisoneisMCPpercentwhich
isspecifiedinline2.Oncethishasbeenspecified,highlighttheentirepageofRcodeandclick“Run”.
Thisshouldloopthroughallsetsofpointsinyour“newlist”fileandproduceauniqueMCPplotforeach
individual(Fig.7).ThiscodeusestheRpackage“adehabitatHR”togenerateMCPsusingthefunction
“mcp”.ThisfunctionisalsopresentintheolderRpackage“adehabitat”.Ifboth“adehabitatHR”and
“adehabitat”areloadedintoRthismayleadtoanerrormessage.Makesure“adehabitat”isnotloaded
beforerunningthiscode.
Figure7:MinimumConvexPolygon(100%MCP)generatedforGPS_A.
19
InadditiontoproducingimagesofMCPhomerangesontopoflocationpoints,thiscode
calculatessummarystatisticsforeachindividual.Thisinformationisstoredinamatrixcalled
“mcpresults”.ThismatrixwillappearasanewlycreatedobjectintheEnvironmenttab.Clickonitto
viewit(Fig.8).Ifthevaluesunder“AREA_HA”seemstrangethisisprobablybecausesomecoordinate
systemotherthanUTMhasbeenspecified.Youcanstillcreatehomerangeswithothercoordinate
systems,buttheareacalculationswillbeincorrect.
Figure8:Summarystatisticsfor100%MCPhomerangescreatedfor3individuals.
IfyouchangetheMCPpercentageandre-runthefunction,itwilldrawnewhomerange
boundariesandcalculatenewareavaluesforeachindividual,however,thefile“mcpresults”willbere-
writtenwiththenewdata.Tosavetheresultsfileasacsvfileusethe“write.csv”functionasbelow:
write.csv(mcpresults, file=”mcpresults.csv”) Thiswillcauseanewcsvfilecalled“mcpresults.csv”toappearinwhateverfilefolderwas
specifiedasyourworkingdirectory.Thiswillbethefilepathwayyouenteredearlieronwhenwewere
creatingalistofSpatialPointsDataFrames.Toverifyyourworkingdirectory,usethefollowing
command:
getwd()
Thiswillprintthefullfilepathwayofyourworkingdirectory.Inmycase,itproducesthe
following:
20
getwd() [1] "F:/R/R for GPS collar data/Test Collar Data"
IfyounavigatetothisfilefolderyouwillalsofindtheMCPshapefilesthatwerecreated.Each
MCPshapefilewillactuallyconsistof4separatefileswiththefollowingextensions:“.dbf”,“.shp”,
“.shx”,and“.prj”.The“.prj”filespecifiestheprojectionandisnecessaryfortheshapefilesyoucreated
toappearinthecorrectlocationswhenyouimportthemintoArcGIS.Thenamesofthevariousfiles
includeboththeoriginalGPSfilenameandtheMCPpercentlevel.Ifyouweretore-runthecodeusing
adifferentMCPpercentlevelthenewshapefileswouldhavedifferentnames,allowingyouto
differentiatebetween,say,100%MCPshapefilesand95%MCPshapefiles.
Figure9:ExampleofMCPshapefileswrittentotheworkingdirectory.Thefile“GPS_A.csv”istheoriginalfileofGPSlocationpoints.Theother4filesmakeupthe100%and95%MCPshapefilesforthisindividual.The“100_MCP”appearingtotherightoftheoriginalfilenameindicatesthattheseare100%MCPshapefiles.Allfilesstartingwith“GPS_A_95”are95%MCPshapefiles.
MAKINGKERNELHOMERANGESINADEHABITATHR
ThiscodeoperatesinasimilarwayasthecodetogenerateMCPs.Italsoloopsthroughall
individualsin“newlist”,andusesadehabitatHRtogeneratefixedkerneldensityhomerangeestimates
(KDE),however,therearemoreinputparametersandyouaremorelikelytogeterrormessageswith
thisparticularcodeblock.Thebestwaytoavoiderrormessagesistomakeabsolutelycertainall
extremeoutlierpointshavebeenremoved.YoucanstillgenerateMCPsusinglocationdatawith
21
extremeoutliers,butkernelhomerangegenerationwilllikelyfailonsuchdatasets.TocreateKDE
polygonsforeachfilein“newlist”loadthecodeblock“CreateKDEadehabitatHR”intotheSource
browsernotebookinRStudio.Userdefinedinputforthissetofcodeconsistsof3lines:
# User defined input. Modify lines below. ############################################################################# per =95 # percent utilization distribution estimated h="href" # bandwidth setting ("href", "LSCV", or user specified number) grid=1000 #############################################################################
Tospecifythepercentdensitycontouratwhichyouwouldliketodrawthehomerange
boundary(i.e.,50%KDE,95%KDE,etc.)modifythenumberafter“per”.Thesmoothingparameter(h)
canbeselectedusingeitherthereferencebandwidth(href)methodorleastsquarescrossvalidation
(LSCV).Alternatively,youmayenteranumberfor“h”ifyouwanttousethesamesmoothingparameter
forallindividuals.“Grid”isatrickyfieldasitspecifiestheextentofthepictureyouaredrawing.Ifthe
valueforgridistoosmallitwillresultinthefollowingerrormessage:
Error in getverticeshr.estUD(ud, per) : The grid is too small to allow the estimation of home-range. You should rerun kernelUD with a larger extent parameter
Ifthishappens,youshouldre-runthecodewithalargergridsize(e.g.,10,000),althoughthis
willslowdowncalculations.Afteryourunthecode,thefilefolderselectedasyourworkingdirectorywill
bepopulatedwithaKDEshapefileforeachindividual.AswiththeMCPshapefiles,eachoftheseKDE
shapefilesactuallyconsistsof4separatefiles,withthefollowingextensions:“.dbf”,“.prj”,“.shp”,and
“.shx”.
Theshapefilenameswillbeabitmorecomplicatedastheywillspecifythepercentdensity
contourforyourhomerangepolygonandthebandwidthselectionmethod.Foranexampleofthe
shapefilesproducedbythiscodeseeFig.10.
22
Figure10:Exampleoutputofcodetocreatekernelhomerangeshapefiles.Thefile“GPS_A.csv”istheoriginalGPSlocationsfile.The4filesbeginningwith“GPS_A_50_LSCV_kernel”areforthe50%KDEproducedusingtheLSCVmethodofbandwidthselection.The4filesbeginningwith“GPS_A_95_href_kernel”areforthe95%KDEproducedusingthehrefmethodofbandwidthselection.
Thekernelhomerangecodealsoproducesaresultsmatrixthatshowssummarydataforall
homerangepolygonscreated.ThisfilecanbefoundintheEnvironmenttabinRStudioandwillbe
named“results”.TheresultsmatrixcontainsIDname,typeofhomerangecreated(HR_TYPE),percent
densitycontour(KERNRL_LEVEL),thenumberofpoints(POINTS),theareaofthehomerangein
hectares(AREA_HA),thesmoothingparameterselected(h_value),andthemethodusedtoselectthe
smoothingparameter(h_meth)(Fig.11).
Figure11:Exampleofoutputresultsfilegeneratedcreatingkernelhomerangesatthe50%densitycontour,usingtheLSCVmethodofbandwidthselection.
23
Figure12:Exampleof95%KerneldensityhomerangecreatedusingtheLeastSquaresCrossValidation(LSCV)procedureforbandwidthselection.Thisfigureshowstheoutputthatthe“Create_Kernel”Rfilesendstothe“Plots”tabinRStudio.
24
Figure13:Exampleof95%KernelDensityhomerangeproducedusingthereferencebandwidth(href)methodofbandwidthselection.Notethatalthoughthehomerangecontoursaretruncatedbytheextentoftheplotareatheshapefilesproducedwillbecomplete.
Onequirktogeneratingkernelhomerangeestimateswiththeabovemethodisthatyouwill
alwaysseethefollowingwarningmessage:
Warning messages: 1: In kernelUD(newlist[[i]], h = h, kern = "bivnorm", grid = grid) : xy should contain only one column (the id of the animals) id ignored
ThiswarningmessageiscausedbecauseweusedSpatialPointsDataFrames,ratherthanSpatial
Pointsobjects,tocreatethehomerangesinadehabitatHR.Ihaveexperimentedwiththisextensively,
andhavecometotheconclusionthatthereisabsolutelynothingwrongwithusingSpatialPointsData
Frameswiththesefunctions.Ifadehabitat,ratherthanadehabitatHR,isloadedintoRhowever,itwill
produceanerrormessageratherthanawarningmessage.Errormessagesindicatethatthefunctiondid
25
notrunasintendedandthatsomethingisseriouslywrong.Warningmessagesindicatethatthefunction
didrunsuccessfully,butthattheremaybeoneortwoirregularitiesworthexaminingbeforeproceeding.
MAKINGKERNELHOMERANGESINRHR
Thepackage“adehabitatHR”isoneofthemostpopularRpackagesforhomerangeanalysis,but
thereareotheroptionsavailable.Arelativelynewpackageis“rhr”,whichstandsfor“Reproducible
HomeRanges”.Thispackageallowsyoutogeneratekernelhomerangesinasimilarmanneras
adehabitatHR,butalsoallowsadditionalmethodsofbandwidthestimation.Thecodeblocktitled
“CreateKDErhr”throughtheobjectsin“newlist”inasimilarwayastheothercodeblocks.Userdefined
inputconsistsofthefollowing3lines:
per = 50 hmeth = rhrHpi # select one (no quotes): rhrHref, rhrHlscv, rhrHpi, rhrHrefScaled h_meth = "rhrHpi" # Same as above but with quotations. You must specify both.
Aswiththepreviouscodeblock,“per”specifiesthepercentdensitycontouryouwishtodraw
(e.g.50%KDE,95%KDE).Thevalues“hmeth”and“h_meth”specifythemethodusedtoselect
bandwidth.Themethodsselected(rhrHref,hrhHlscv,rhrHpi,andrhrHrefScaled)needtobeidenticalfor
both“hmeth”and“h_meth”,however,quotationmarksmustbeplacedaroundthenamefor“h_meth”
butnotfor“hmeth”.
Afterthishasbeenaccomplished,highlightthecodeandclickRun.InthePlotwindow,two
differentplotswillbecreatedforeachindividual.ThefirstwillshowtheKDEasarasterwiththe
specifiedkernellevelindicatedbyasolidblacklineandanimalrelocationpointsgivenassmallcrosses
(Fig.14).Thesecondplotwillshowonlytheisoplethsdrawnforwhicheverkerneldensitycontour(per)
wasselected(Fig.15).Theisoplethwillbeexportedasashapefile,completewithprojection,tothe
workingdirectoryinanidenticalmannerasinthepreviouscodeblock.
26
TheresultsfileforthiscodeblockissimilartothatcreatedusingtheadehabitatHRpackage,but
withoneadditionalfield.Becausesomeofthebandwidthselectionmethodsrelyontwoparameters,
makingreproduciblehomerangesrequirestwovaluestobesavedforeachhomerangeestimate.These
aregivenas“h_value1”andh_value2”.Formethodsthatrequireonlyonevalue(e.g.,rhrHref)both
fieldswillbepresentintheresultsfilebuttheywillbeidenticaltoeachother.Formethodsthatrequire
twovalues(e.g.,rhrHpi)thetwovalueswillbedifferent.Theresultsfilewillappearasamatrixinthe
Environmentwindowwiththename“rhr_results”(Fig.16).
Figure14:Kerneldensityestimateasarasterfilewith95%densityisoplethdrawninblackandanimalrelocationsshownasblackcrosses.
27
Figure15:Kerneldensityestimate,drawnatthe95%level.
Figure16:Resultsfilecreatedusingpackage“rhr”andthe“rhrHpi”methodofbandwidthselection.Notethat“h_value1”and“h_value2”aredifferentbecausetwouniquevaluesarerequiredforthismethodofbandwidthselection.
ADDINGFIELDSTOGPSLOCATIONSFILES
Inadditiontogeneratinghomerangeshapefiles,theremaybefieldsthatyouwanttoaddto
youroriginalGPSlocationsfiles.Forexample,ifyourGPScollarscollectcoordinatesinLatitude
Longitudeformat,youmaywanttore-projectthemasUTMcoordinatesanddisplaybothcoordinate
systemsascolumnsintheinputfile.Additionally,youmaywanttoconverttimezonestodisplaydate
andtimebothinCoordinatedUniversalTimeandinthelocaltimezone.Perhapsyouwantarobustand
ecologically-meaningfulwayofseparatingnightfromdayusingthesun’sazimuthabovetheearth.
28
Thecodeblock“CreateNewFields”isthemostcustomizablecodeblockinthismanual.The
functionsIincludedaremainlyintendedtoprovideexamplesofthetypesofoperationsthatcanbe
automatedusingR.IwouldencourageanyonewithabitofexperienceinRtoplayaroundwiththisto
generatenewfieldsfortheirparticulardatasets.Thebasicprocessforaddinganewfieldtoalllocation
filesistoinsertalineintothe“for”loop,somewherebetweenlines33and49.Thenameofthenew
fieldappearstotherightofthe“$”,after“infile”.Theargumentsforthefunctionyouarerunningwillbe
locatedtotherightofthe“<-“onthatline.Ittakessomepracticetogetthisworkingforcomplicated
functions,butitisworthlearning.
Beforeusingthiscode,afewimportantpointsneedtobemade.First,thefunctionIcreatedto
calculatetraveldistanceusesthePythagoreantheorem.Therefore,itcanonlybeusedwithCartesian
coordinatesystems,suchasUTM.Ifyoure-projectpointsfromLatitude-LongitudetoUTM,thecodewill
workfinewithoutmodification.Secondly,thefunctionthatcalculatessunazimuthrequires,asinput,
theapproximatelatitudeandlongitudeofyourstudyareaindecimaldegrees.Usually,reportingthe
coordinatesofsomepointnearyourstudyarea(e.g.,closesttown)isgoodenough.Specifythelatitude
andlongitudeyouwouldliketouseunder“ref_lat”and“ref_long”respectively,intheuserdefined
inputportionofthecodeblock.
UserdefinedinputisrelativelysimpleforthisRfile.Specifythenameofthexaxisforyournew
coordinatesystemunder“newx”.Specifythenameoftheyaxisforyournewcoordinatesystemunder
“newy”.Specifythenewtimezonecodeunder“new.timezone”.Specifytheoutputprojectionunder
“output.projection”.Thisstepisactuallysomewhatredundantifyoualreadyusedthecodeblock“Re-
projectPointstoUTM”,however,Iincludeditincasetheuserwantstochangepointstosomeother
coordinatesystem.
29
BROWNIANBRIDGEMOVEMENTMODELS
Afteryourunthecodeblock“CreateNewFields”,youshouldhavetwolistsinyourworking
environment.Thefirstlistis“newlist”,whichconsistsofalistofSpatialPointsDataFramesprojectedin
whatevercoordinatesystemwasselectedatthe“ReprojectingPoints”step.Thesecondlistiscalled
“newlist_df”anditconsistsofalistofdataframes(notSpatialPointsDataFrames)populatedwithall
fieldsspecifiedinthe“CreateNewFields”codeblock.Manyofthefunctionsthatwereaddedtothe
“CreateNewFields”codeblockarejusttodemonstratethecoolthingsyoucandowithR.Afewofthe
newfields,however,arenecessaryforcreatingBrownianbridgemovementmodels.Specifically,
coordinatesinUTM(orsomeotherCartesiancoordinatesystem)arenecessary,asisafieldspecifying
thetimelaginminutesbetweenconsecutiveGPSfixes.TheBrownianbridgemovementmodelisan
approachtogeneratingutilizationdistributionsthatisspecificallyintendedforauto-correlatedlocation
data.ItisusedwhenGPSfixesaretakenatsuchhighfrequenciesthatconsecutivepointscannotbe
consideredindependent.OfthesamplefilesinAppendixB,onlythefiles“GPS_D”and“GPS_E”have
thisstructure.TheBrownianbridgemovementmodelisinappropriateforfiles“GPS_A”,“GPS_B”and
“GPS_C”,however,youcanstillcreateBrownianBridgesfromthesefilesifyouareinterestedinseeing
howtheresultsdifferfromthosecreatedfortrulyauto-correlateddata.
Iwouldrecommendthefollowingstepsforusingthe“CreateBBMM”codeblockforthefirst
time.First,savethesampledatafilesnamed“GPS_D”and“GPS_E”ascsvfilesinafilefolderwithno
otherfiles(i.e.,remove“GPS_A”,“GPS_B”,and“GPS_C”).Next,runthroughthefollowingcodeblocks:
“CreateListofSpatialPointsDataFrames”,“Re-projectPointstoUTM”,and“CreateNewFields”.Don’t
worryaboutcreatingMCPorKDEhomerangeestimatesorplottingpointstoremoveoutliersforthese
sampledatasets.Next,loadthecodeblocktitled“CreateBBMM”intotheSourcebrowsernotebook.
TheoptionsinvolvedincreatingBrownianbridgemovementmodelsareconsiderablymore
complicatedthanthoseforanyoftheprevioussteps.Thefunction“brownian.bridge”estimates
30
probabilityofuseacrossaspatialgridofpointsbaseduponthelocationsofanimalrelocationpointsand
thetimelagbetweenthesepoints.Inorderforthisfunctiontowork,youwillneedtospecifythisgridof
points.Therearetwowaystodothis:thefirstistospecifyonlythecellsizeandtoallowtheBBMM
packagetoestimatetheextentoftheavailabilitygrid,thesecondistomanuallycreateagridofpoints
andtellthefunctiontoestimateprobabilityofuseforeachpointinthisgrid.Thefirstmethodrequires
lessuserinput,butitoftenproducesanavailabilitygridthatistoosmalltocapturethefullutilization
distribution.Irecommendusingbothmethodsonthesampledatafilesbeforeusingthiscodeblockon
yourowndata.Todothis,modifythefollowinglinesofuser-definedinput:
X = "UTM_X" # The column name of your x coordinate Y = "UTM_Y" # The column name of your y coordinate loc.error = 20 maxlag = 60 levels = 95 cell.size = 10 # change to NULL if area.grid is used grid = NULL # if area.grid is created Null status will be removed
Thevalues“X”,and“Y”shouldbeself-explanatory.Thevalue“loc.error”referstothelocation
errorexpectedforyourrelocationpoints.Itcaneitherbeasinglevalueoravectorofvalues.Thevalue
“maxlag”isthemaximumtimelaginminutesthatistobeallowedforBrownianbridgecalculation.The
value“levels”isthepercentcontourtobedrawnaroundpointsintheavailabilitygrid.Itisanalogousto
thedensitycontourinakernelhomerange.Thevalue“cell.size”isthesizeofeachpointinthegrid.
Smallervaluesof“cell.size”willresultinahigher-resolutionpictureofutilizationdistribution,but
increasecomputationtime.Thevalue“grid”isthenameoftheavailabilitygridtobeusedifyouare
manuallyspecifyinganavailabilitygrid.Ifyouwanttospecifyonly“cell.size”andhavethefunction
estimatetheavailabilitygridforyou,thisvalueneedstobeNULL.
Next,ifyouwantthepackagetoestimatetheavailabilitygridforyou,skipallthelinesofuser-
definedinputbelowthelineofhashtags(#).Specifically,youwillbeskippingtheselines:
31
# Optional user defined input. Skip if “cell size” method of grid creation is used. ############################################################################# LeftX=646000 RightX=648000 TopY=2945000 BottomY=2942000 size=10 xcoords<-seq(from=LeftX, to=RightX, by=size) ycoords<-seq(from=BottomY, to=TopY, by=size) x<-rep(xcoords, times=length(ycoords)) y<-rep(ycoords, each=length(xcoords)) grid<-data.frame(x,y) cell.size = NULL # over-rides earlier cell size if run #############################################################################
Theabovecodegeneratesauniformrectangulargridofpoints.Itisactuallyaveryusefulbitof
codeforvariousoperationsanditisworthplayingaroundwithtounderstandhowitworks.Basically,
thevalues“LeftX”,“RightX”,“TopY”,and“BottomY”specifytheminimumXvalue,maximumXvalue,
maximumYvalue,andminimumYvaluerespectively.Thevalue“size”specifieshowfarapart(in
meters)youwantthepointstobe.Notethatthelastlineofcodeinthisblockre-setsthevalue
“cell.size”toNULL.Thisisbecausethe“brownian.bridge”functionrequireseithercellsizeoran
availabilitygrid(butnotboth)tobespecified.
Afterskippingtheabovecode,highlighteverythingbelowthesecondlineofhashtagsandclick
run.Dependingonthenumberoffilesyouhaveandthecellsizeyouspecified,thiscouldtakeawhileto
run.Eventually,youshouldseeplotssimilartoFigures16and17appearinginyourPlotswindow.
32
Figure16:PlotofaBrownianbridgemovementmodelwith95%probabilitycontourdrawninblack,movementtrajectoryrepresentedbyaredline,andrelocationpointsrepresentedbyreddots.ThismovementtrajectorywasadequatelycapturedbytheavailabilitygridcreatedbyBBMM.
Figure17:PlotofaBrownianbridgemovementmodelwith95%probabilitycontourdrawninblack,movementtrajectoryrepresentedbyaredline,andrelocationpointsrepresentedbyreddots.ThismovementtrajectorywasnotadequatelycapturedbytheavailabilitygridcreatedbyBBMM. Noticethattheplotfor“GPS_E”iscutoffbythemarginsoftheplotimage.Thisisnotsimplya
quirkoftheRplottingfunctionthatwillgoawayoncewegenerateshapefiles(aswasthecasewith
kernelpolygons).Anyshapefilesexportedusingthisfunctionwillalsobecutoff.Theproblemliesinthe
33
methodusedtospecifytheavailabilitygrid.Usually,specifyingonlythecellsizeandallowingtheBBMM
packagetogeneratetheavailabilitygridworksfine.Inthiscase,however,theavailabilitygridisnot
largeenoughtocapturethefull95%probabilitycontour.
Incaseslikethis,wewillneedtospecifytheavailabilitygridmanually.JustlookingatFigure17,
wecouldprobablyguesswhatourmaximumandminimumXandYcoordinatesshouldbetocapture
thefullutilizationdistribution.Thecodeprovidedspecifiesaminimumxvalueof646000,amaximumx
valueof648000,amaximumyvalueof2945000,andaminimumyvalueof2942000.Tomanually
specifyanavailabilitygridwiththisextent,wesimplyhighlighttheentire“CreateBBMM”codeblock,
includingthesectionbracketedbyhashtags,andclickrun.ThisshouldproduceplotssimilartoFigures
18and19.
Figure19doesn’tlooktooimpressivesincetheavailabilitygridcreatedwastoolarge.However,
thiswon’taffecttheshapefilegeneratedforthisprobabilitycontour.Unlessyouareplanningonusing
theplotscreatedinRforapublicationorposter,Iwouldn’tworryaboutthistoomuch.Youcansimply
exporttheshapefileusingthiscodeblockandviewitinArcGIS.
The“CreateBBMM”codeblockgenerates3outputfilesperindividual.ThefirstisaSpatialLines
shapefileshowingwhicheverprobabilitycontourwasspecifiedunderthevalue“levels”.Aswithall
othershapefilesgeneratedinthismanual,thisactuallyconsistsof4separatefiles,oneofwhich
specifiestheprojection.Thesecondfileisapointsshapefileshowingpointsintheavailabilitygridwith
probabilityofusegiveninthe“z”column.Pointswithprobabilityofuse<0.00000001areremoved.
ThesepointscanbeviewedinArcGISandcolorcodedaccordingtothe“z”columntogiveapictureof
theinternalanatomyofthehomerange(Fig.20).Thethirdfileisacsvfileshowingthesamevaluesas
thepointsshapefile,butlackingspatialprojectioninformation.
34
Figure18:PlotofaBrownianbridgemovementmodelwith95%probabilitycontourdrawninblack,movementtrajectoryrepresentedbyaredline,andrelocationpointsrepresentedbyreddots.Availabilitygridwasspecifiedmanually.
Figure19:PlotofaBrownianbridgemovementmodelwith95%probabilitycontourdrawninblack,movementtrajectoryrepresentedbyaredline,andrelocationpointsrepresentedbyreddots.Availabilitygridwasspecifiedmanually.
BoththeSpatialLinespolygonsshowingprobabilitycontours(e.g.,50%and95%)andthepoint
gridshapefilescanbeviewedinArcGIS.Thepointsinparticularcanprovideaninterestingpictureof
35
animalspaceusesincetheyshowhowprobabilityofusevariesthroughouttheanimal’shomerange.
The“z”valuesinthesefilesspecifyprobabilityofuse,andyoucanmakeacolor-codedrepresentationof
ananimal’sutilizationdistributionbysettingacolorscaletothisvariable(Fig.20).
Figure20:MapproducedinArcGISshowingBrownianbridgepointsshapefileandBrownianbridge95%probabilitycontour.The95%probabilitycontourisshownbythesolidredline.Pointsthatarecoloredredhaveahigherprobabilityofusethanpointscoloredyelloworgreen.
FINDINGCODESFORCOORDINATEREFERENCESYSTEMS
SpecifyingtheCoordinateReferenceSystem(CRS)isprobablythetrickiestparttousingRfor
spatialdataanalysis.SpecifyingtheCRSrequiresthatpackages“rgdal”and“sp”beloaded.Many
vignettesforpackagesrelatingtospatialecology(e.g.,adehabitatHR)omitanydiscussionofCRS.You
cangeneratehomerangeestimatesandstudyanimalmovementusingsuchpackageswithout
consideringCRS,buteventuallythiswillcauseproblems.Ifyouexportyourdatatoshapefiles,andlater
viewtheseshapefilesinArcGIS,theymightappearfarfromyourstudyarea.Thebestwaytoanalyze
actualwildlifetelemetrydataistospecifythecorrectCRSfromthebeginning,andusethefunction
36
“spTransform”totransformtheseasneeded.AnexplanationofhowtodeterminetheCRSofyourdata
canbefoundat:
https://www.nceas.ucsb.edu/~frazier/RSpatialGuides/OverviewCoordinateReferenceSystems.pdf.
Hopefully,youeitherknowthecoordinatereferencesystemusedforyourdataorcaneasilyfind
it.Ifyourxanyycoordinatesaregivenindecimallatitudelongitudecoordinates,youwillprobablyuse
WGS84,whichisspecifiedbythefollowingcode:“+init=epsg:4326”.Youcanmakeadataframeofall
CRScodesrecognizedbyRusingthefollowingcommand:
EPSG<-make_EPSG() Thisproducesadataframewith5,078rowsshowingallCRSsrecognizedbyR(Fig.21).Ifyouare
tryingtotransformyourcoordinatestoanuncommonCRSyoucansearchthisdataframetofindthe
codeneeded.Mostlikely,yourGPSdatawillbedeliveredasdecimallatitudeandlongitudecoordinates,
andyouwillbetransformingittoUniversalTransverseMercator(UTM).
Figure21:ScreencaptureofasmallportionofthedataframeofallpossibleCRSsavailableinR.Thefield“code”specifiestheepsgcodewhichcanbeusedtospecifytheCRS(e.g.,“+init=epsg:26908”specifiesNAD83/UTMzone8N).Thefield“note”describestheCRs,andthefield“prj4”listsalltheargumentsforthatparticularCRS.
ScrollingthroughthedataframeofpossibleCRSsforRcanbeoverwhelming,butthereareways
tonarrowthisdownsubstantially.Let’ssayIwantedtosubsetthisdataframetoshowonlythose
recordswith“NAD83”includedsomewhereinthenotes.Thiswouldbethesyntaxfordoingso:
37
tmp<-EPSG[grep("NAD83", EPSG$note),]
Thiscodecreatesanewdataframecalled“tmp”thatshowsonlythoserowswith“NAD83”in
thenotes.Youdon’tneedtounderstandtoomuchabouthowthiscodeworks,butifyouplayaround
withityoucanseethatyoucanfurthersubsetthedataframebymodifyingthecodeabove.For
example:
tmp2<-EPSG[grep("proj=utm", tmp$prj4),]
Thiscreatesanewdataframecalled“tmp2”thatselectsrowsfrom“tmp”thathavethetext
“proj=utm”somewhereintheprj4column.Ifyouaretransforminglatitude/longitudecoordinatesto
UTMinSouthTexas,Iwouldrecommendkeepingthevaluesgivenunder“input.projection”and
“output.projection”exactlyastheyareinallcodeblocksgiveninAppendixA.
SPECIFYINGDATEANDTIMEFORMAT
Thecodeblocksinthismanualtreatdateandtimeasasingledate/timefieldinPOSIXctformat
withrelevanttimezoneinformation.Youdon’treallyneedtoknowwhatPOSIXctformatistogetthe
codetowork,butyoushouldbeabletospecifythecorrectdate/timeformatsothatthetimelagfieldis
calculatedcorrectlyandsoyoucanusepackagestoaccuratelycalculatethingslikemoonphaseandsun
angle.Thismanualusesthefunction“parse_date_time”intheRpackage“lubridate”tocombinedate
andtimefieldsintoasinglefieldandassignitthecorrectPOSIXctformat.Iwouldrecommendtakinga
lookatthe“lubridatecheatsheet”availableat
http://blog.yhat.com/static/pdf/R_date_cheat_sheet.pdf.Inshort,youwanttomakesurethatyou
specifythecorrectformatunder“datetime.code”intheuserdefinedinputportionof“CreateListof
SpatialPointsDataFrames”.Theformatprovidedforthesampledatais“dmy_HMS”whichmeansthat
38
daycomesfirst,followedbymonth,year,(aspace),hour,minute,andsecond.Ifyouwereto
accidentallychangethisto“mdy_HMS”yourdateswouldbeincorrect.
AlotofGPScollarsprovidedateandtimeinbothUTCandthelocaltimezone.Inmy
experience,however,thesefilesoftentonotcorrectlyaccountfordaylightsavingstime.Unlessyouare
confidentthatthelocaltimefieldinyourinputlocationsfilescorrectlyaccountsfordaylightsavings
time,IwouldrecommenddiscardingthelocaltimezonefieldprovidedbytheGPScollarsand
recalculatingthisonyourownusing“lubridate”.Thisisfairlystraightforwardandisactuallydonefor
youinthecodeblock“CreateNewFields”.Yousimplyhavetospecifythecorrecttimezonecodeinthe
userdefinedinputsectionunder“new.timezone”.Thetimezonecodeprovidedintheexampledata
(“CST6CDT”)isCentraltime,withdaylightsavingstimeincluded.
TROUBLESHOOTING
MybiggestcriticismofRisthattheerrormessagesareextremelydifficulttointerpret.A
commonmistakeRusersmakeisfailingtospecifythecorrectfilepathwaytotheinputdata.Let’ssayI
usedbackslashesinsteadofforwardslashesunder“input”forthecodeblock“CreateListofSpatial
PointsDataFrames”.Inotherwords,Ityped“F:\R\R for GPS collar data\Test”insteadof
“F:/R/R for GPS collar data/Test”.Thiswouldproducethefollowingerrormessage:
Error in datalist[[i]] : subscript out of bounds
Thisisnotexactlyhelpful.Ratherthantrytogooglespecificerrormessagestofigureoutwhatis
goingon,Iwouldrecommenddouble-checkingboththeinputfilesandtheuserdefinedinputcodeof
eachcodeblocktomakesuretheyareassimilaraspossibletotheexamples.Ifyouhavefileswith
differentcolumnheadingsforxandycoordinates,forexample,thiswilldefinitelycauseproblems.
39
Anothercommonproblemisnothavingtherequiredpackagesloaded.Theerrormessagesin
thiscasewillbealittleeasiertointerpret.Let’ssayIdidnothavethepackage“sp”installedwhenIran
“CreateListofSpatialPointsDataFrames”.Thisproducesthefollowingerrormessage:
Error in coordinates(xy) <- c(x, y) : could not find function "coordinates<-"
Whatthiserrormessagemeansisthatyoutriedtousethefunction“coordinates”thatwasnot
availableinyourworkingenvironment.Itwasnotavailablebecausethepackagecontainingthisfunction
(sp)wasnotloaded.
Havingrandomjunkinyourinputdatafilescanalsocausemajorproblems.Ifacolumnismeant
tocontaindatainaspecificformat(e.g.,numerical),includingjustasinglecellcontainingatextstring
(e.g.,“unknown”,or“missing”)willthrowawrenchinthings.ItisusuallyoktohaveNAoperatorsin
yourdata,asRisabletorecognizecommonNAoperators,however,youshouldn’tmixandmatchNA
operators.Forexample,youdon’twanttohavesomecellswith“NA”andotherswith“N/A”or“na”.
TheresultofrandomjunkinyourinputfilesisoftenthatRwillreadaspecificfieldasafactorrather
thanasacharacterornumericalfield.Thiscancauseproblemsif,forexample,“Latitude”ismeanttobe
anumericalvaluebutRrecognizesitasafactor.Thiswillmakeitimpossibletoperformany
mathematicaloperationsonthisfieldandwillpreventyoufrombeingabletoplotpointsorcreate
SpatialPointsDataFrames.
40
APPENDIXAInstallRequiredPackages#Installrequiredpackages#RunthiscodebeforeusinganyothercodeblocksusePackage<-function(p){if(!is.element(p,installed.packages()[,1]))install.packages(p,dep=TRUE)require(p,character.only=TRUE)}pkg<-c("sp","lubridate","rgdal","maptools","adehabitatHR","rgdal","raster","BBMM","lunar","oce","move")lapply(pkg,usePackage)lapply(pkg,library,character.only=TRUE)install.packages("rhr",repos=c("http://78.47.85.98/R","http://cran.rstudio.com/"),dep=TRUE)library(rhr)
41
CreateListofSpatialPointsDataFrames#CreateListofSpatialPointsDataFrames#Animallocationsmustbesavedasseparatecsvfilesinasinglefolder#NamesforxandycoordinatesandDateandTimefieldsmustbeidentical#CreatedbyJohnLeonard08_23_2016#Userdefinedinput.Modifylinesbelow.#########################################################################input="J:/R/RforGPScollardata/TestCollarData"x="Longitude"#Thecolumnnameofyourxcoordinatey="Latitude"#Thecolumnnameofyourycoordinatedatetime.code="dmy_HMS"#modifythisusingdocumentationinLubridateDatecolumn="GMT.Date"Timecolumn="GMT.Time"timezone="UTC"input.projection="+init=epsg:4326"
na.operator="N/A"#########################################################################Loadrequiredpackagesrequire(sp)require(lubridate)#Setworkingdirectoryandcreateemptylisttostorecsvfiles.setwd(input)datalist<-list()files<-list.files(input)files#ReadinCSVfiles.for(fileinfiles){stem<-gsub("\\.csv$","",file)datalist[[stem]]<-(read.csv(file,stringsAsFactors=FALSE,na.strings=na.operator))}#LoopthroughcsvfilesandcreatealistofSpatialPointsDataFramesnewlist<-list()#forloopforgoingthrougheachfilefor(iin1:length(datalist)){infile=datalist[[i]]infile=subset(infile,infile[,x]!="NA")infile=subset(infile,infile[,y]!="NA")Date=infile[,Datecolumn]Time=infile[,Timecolumn]infile$Date.Time<-parse_date_time(paste(Date,Time),datetime.code,tz=timezone)xy=infile[,c(x,y)]
42
coordinates(xy)<-c(x,y)proj4string(xy)<-CRS(input.projection)infile2<-SpatialPointsDataFrame(xy,infile)name=names(datalist[i])newlist[[i]]<-infile2names(newlist)[i]<-name}rm(Date,file,files,i,infile2,name,Time,xy,Datecolumn,input,pkg,stem,Timecolumn,timezone,usePackage)#removeunwantedobjects
43
PlotPointstoRemoveOutliers#Plotallpointstoremoveoutliers#Tobeusedonthe"newlist"object#SimpleVersion.Onlyremovesoutliersbycoordinates#CreatedbyJohnLeonard08_23_2016for(iin1:length(newlist)){plot(newlist[[i]]@coords,main=names(newlist[i]))}#Firstmakeduplicateofnewlistcallednewlist2justtobesafenewlist2<-newlist#Modifycodebelowtoselectmaximumorminimumxoryvalues#Codebelowmakes"27"themaximumlatitudevalueforGPS_Anewlist2$GPS_A<-subset(newlist2$GPS_A,newlist2$GPS_A@coords[,y]<27)#Codebelowmakes"-97.55"theminimumlongitudevalueforGPS_Bnewlist2$GPS_B<-subset(newlist2$GPS_B,newlist2$GPS_B@coords[,x]>-97.55)newlist2$GPS_C<-subset(newlist2$GPS_C,newlist2$GPS_C@coords[,y]>26.55)#Plotagaintoseeifalloutliershavebeenremovedfor(iin1:length(newlist2)){plot(newlist2[[i]]@coords,main=names(newlist2[i]))}#Ifitlooksgood,convertnewlist2backintonewlist.#Note:Thiscannotbeundone!newlist<-newlist2
44
Re-projectPointstoUTM
#Re-projectPointstoUTM#CreatedbyJohnLeonard08_23_2016#Userdefinedinput.Modifylinebelow.######################################################################output.projection="+proj=utm+zone=14+datum=NAD83"#######################################################################loadrequiredpackagesrequire(sp)require(lubridate)require(rgdal)#forloopforgoingthrougheachfilefor(iin1:length(newlist)){infile=newlist[[i]]infile=spTransform(infile,CRS(output.projection))name=names(newlist[i])newlist[[i]]<-infilenames(newlist)[i]<-name}rm(i,name)#removeunwantedobjects
45
ExportPoints#ExportPoints#Exportpointsasshapefileswithprojection#Note:AllPOSIXctfieldsmustbeconvertedtocharacter#CreatedbyJohnLeonard08_23_2016for(iin1:length(newlist)){infile<-newlist[[i]]infile$Date.Time<-as.character(infile$Date.Time)name=names(newlist[i])writePointsShape(infile,name,factor2char=TRUE)cat(showWKT(proj4string(newlist[[i]])),file=paste0(name,".prj"))}rm(i,name)#removeunwantedobjects
46
CreateMCP
#CreateMCP#PlotsMinimumConvexPolygonHomeRangesandexportsshapefiles#SpatialcoordinatesshouldbeUTMforcorrectareacalculation#CreatedbyJohnLeonard08_23_2016#Userdefinedinput.Modifylinebelow.##################################################################per=100#percentMCPtocreate(e.g.95,100,etc.)###################################################################Loadrequiredpackagesrequire(sp)require(maptools)require(adehabitatHR)require(rgdal)#InitializeMatrixtostoreresultsmcpresults=matrix(nrow=0,ncol=5)colnames(mcpresults)<-c("ID","HR_TYPE","MCP_LEVEL","POINTS","AREA_HA")for(iin1:length(newlist)){xy.mcp=SpatialPoints(newlist[[i]]@coords)mcp.out=mcp(xy.mcp,percent=per,unout="ha")plot(xy.mcp,main=names(newlist[i]))plot(mcp.out,add=TRUE)name=names(newlist[i])area=mcp.out$arearow=nrow(newlist[[i]])mcpresults=rbind(mcpresults,c(name,"MCP",per,row,area))writePolyShape(mcp.out,paste0(name,"_",per,"_MCP"),factor2char=TRUE)cat(showWKT(proj4string(newlist[[i]])),file=paste0(name,"_",per,"_MCP.prj"))}rm(area,i,mcp.out,name,per,row,xy.mcp)
47
CreateKDEadehabitatHR#CreateKDE#Createandexportkernelhomerangeswithprojection#Important!!!UseadehabitatHRNOTadehabitat.#CreatedbyJohnLeonard08_23_2016#Userdefinedinput.Modifylinesbelow.#######################################################################per=95#percentutilizationdistributionestimatedh="href"#bandwidthsetting("href","LSCV",oruserspecifiednumber)grid=1000########################################################################Loadrequiredpackagesrequire(sp)require(maptools)require(adehabitatHR)require(rgdal)#Initilizingmatrixforstoringresultsresults=matrix(nrow=0,ncol=7)colnames(results)<-c("ID","HR_TYPE","KERNEL_LEVEL","POINTS","AREA_HA","h_value","h_meth")for(iin1:length(newlist)){name=names(newlist[i])ud<-kernelUD(newlist[[i]],h=h,kern="bivnorm",grid=grid)ver=getverticeshr(ud,per)area=ver$area#gethomerangepolygonareah_value=ud@h$hh_meth=ud@h$methrow=nrow(newlist[[i]])plot(newlist[[i]]@coords,main=names(newlist[i]))plot(ver,add=TRUE)writePolyShape(ver,paste0(name,"_",per,"_",h,"_kernel"),factor2char=TRUE)cat(showWKT(proj4string(newlist[[i]])),file=paste0(name,"_",per,"_",h,"_kernel.prj"))results=rbind(results,c(name,"KERNEL",per,row,area,h_value,h_meth))}rm(area,grid,h,h_meth,h_value,infile,name,per,row,ud,ver)#removeunwantedobjects#Didn'twork?MakesureadehabitatHRandNOTadehabiatisloaded!
48
CreateKDErhr#CreatingKernelHomeRangeswithrhr#Createsandexportskerneldensityisoplethsasshapefiles#Allowsgreaterflexibilityinselectingbandwidth#CreatedbyJohnLeonard08_23_2016#Userdefinedinput.Modifylinesbelow.############################################################################per=50hmeth=rhrHpi#selectone:rhrHref,rhrHlscv,rhrHpi,rhrHrefScaledh_meth="rhrHpi"#Sameasabovebutwithquotations.Youmustspecifyboth.#############################################################################Loadpackagesrequire(rhr)require(sp)require(maptools)require(rgdal)rhr_results=matrix(nrow=0,ncol=8)colnames(rhr_results)<-c("ID","HR_TYPE","KERNEL_LEVEL","POINTS","AREA_HA","h_value1","h_value2","h_meth")for(iin1:length(newlist)){name=names(newlist[i])xy<-SpatialPoints(newlist[[i]]@coords)bandwidth=hmeth(xy)$hkde<-rhrKDE(xy,h=bandwidth,levels=per)name=names(newlist[i])row=nrow(newlist[[i]])area=(rhrArea(kde,levels=per)$area/10000)h_value1=bandwidth[1]h_value2=bandwidth[2]plot(kde,main=name)plot(xy,add=TRUE)iso<-rhrIsopleths(kde,levels=per)plot(iso,main=name)writePolyShape(iso,paste0(name,"_",per,"_",h_meth),factor2char=TRUE)cat(showWKT(proj4string(newlist[[i]])),file=paste0(name,"_",per,"_",h_meth,".prj"))rhr_results=rbind(rhr_results,c(name,"RHR",per,row,area,h_value1,h_value2,h_meth))}rm(area,bandwidth,h_meth,h_value1,h_value2,i,iso,kde,name,per,row,xy,hmeth)#removeunwantedobjects
49
CreateNewFields#CreateNewFields#PopulatesGPSlocationsfileswithnewfieldsandwritestocsvfiles#"newlist"isalistofSpatialPointsDataFrameswithprojection#traveldistfunctiononlyworkswithCartesiancoordinatesystem#newlist_dfwillbealistofdataframes(notSpatialPointsDataFrames)#CreatedbyJohnLeonard08_23_2016#Userdefinedinput.Modifylinesbelow.##########################################################################ref_lat=26.55#ApproximateLatitudeforsunazimuthcalculationref_long=-97.42#ApproximateLongitudeforsunazimuthcalculationnewx="UTM_X"newy="UTM_Y"new.timezone="CST6CDT"output.projection="+proj=utm+zone=14+datum=NAD83"#########################################################################require(sp)require(rgdal)require(lubridate)require(lunar)require(oce)traveldist<-function(x,y){sqrt((append(0,diff(x))^2+append(0,diff(y))^2))}newlist_df<-list()#forloopforgoingthrougheachfilefor(iin1:length(newlist)){infile=newlist[[i]]infile=spTransform(infile,CRS(output.projection))xy=data.frame(coordinates(infile))colnames(xy)[1]<-newxcolnames(xy)[2]<-newyinfile=data.frame(infile@data)infile=cbind(infile,xy)infile$Local.Date.Time<-with_tz(infile$Date.Time,tzone=new.timezone)infile$Year<-strftime(infile$Date.Time,format="%y")infile$Month<-strftime(infile$Date.Time,format="%m")infile$Day<-strftime(infile$Date.Time,format="%d")infile$Hour<-strftime(infile$Date.Time,format="%H")Timelag.sec<-c(NA,(diff(as.numeric(infile$Date.Time))))infile$Timelag.min<-Timelag.sec/60infile$Traveldist<-traveldist(infile[,newx],infile[,newy])infile$Velocity<-infile$Traveldist/infile$Timelag.minsun<-sunAngle(infile$Date.Time,longitude=ref_long,latitude=ref_lat,useRefraction=TRUE)infile$sun.azimuth<-sun$azimuthinfile$moonphase<-lunar.phase(infile$Date.Time,name=TRUE)
50
name=names(newlist[i])#Createanamebasedonfilenamenewlist_df[[i]]<-infilenames(newlist_df)[i]<-namewrite.csv=write.table(infile,file=paste0(name,"_modified.csv"),sep=",",col.names=TRUE,row.names=FALSE,qmethod="double")}rm(infile,xy,i,name,newx,newy,ref_lat,ref_long,sun,Timelag.sec,write.csv)#Removeunwantedobjects
51
CreateBBMM#CreateBrownianBridgeMovementModels#Recommendedtousethisafter"CreateNewFields"#newlist_dfislistofDataFramesnotSpatialPointsDataFrames#Shouldonlybeusedonhigh-frequencytelemetryfiles#CreatedbyJohnLeonard08_23_2016#Userdefinedinput.Modifylinesbelow.##################################################################X="UTM_X"#ThecolumnnameofyourxcoordinateY="UTM_Y"#Thecolumnnameofyourycoordinateloc.error=20maxlag=60levels=c(95)cell.size=10#changetoNULLifarea.gridisusedgrid=NULL#ifarea.gridiscreatedNullstatuswillberemoved###################################################################Optionaluserdefinedinput.Skipif"cellsize"#methodofgridcreationisused.##################################################################LeftX=646000RightX=648000TopY=2945000BottomY=2942000size=10xcoords<-seq(from=LeftX,to=RightX,by=size)ycoords<-seq(from=BottomY,to=TopY,by=size)x<-rep(xcoords,times=length(ycoords))y<-rep(ycoords,each=length(xcoords))grid<-data.frame(x,y)cell.size=NULL#over-ridesearliercellsizeifrun##################################################################require(BBMM)require(raster)require(maptools)require(rgdal)for(iin1:length(newlist_df)){infile=newlist_df[[i]]name=names(newlist_df[i])BBMM<-brownian.bridge(infile[,X],infile[,Y],time.lag=infile$Timelag.min[-1],location.error=loc.error,cell.size=cell.size,area.grid=grid)x<-BBMM$x[BBMM$probability>=0.00000001]y<-BBMM$y[BBMM$probability>=0.00000001]
52
z<-BBMM$probability[BBMM$probability>=0.00000001]tmp.df<-data.frame(x,y,z)contours<-bbmm.contour(BBMM,levels=levels,locations=cbind(infile[,X],infile[,Y]),plot=TRUE)title(main=name)out.raster<-rasterFromXYZ(tmp.df,crs=CRS(output.projection),digits=2)raster.contour<-rasterToContour(out.raster,levels=contours$Z)writeLinesShape(raster.contour,paste0(name,"_",levels,"_BBMM"),factor2char=TRUE)cat(showWKT(proj4string(newlist[[1]])),file=paste0(name,"_",levels,"_BBMM.prj"))write.csv(tmp.df,file=paste0(name,"_BBMM.csv"))tmp.xy<-tmp.df[,c(1:2)]coordinates(tmp.df)<-tmp.xyproj4string(tmp.df)<-CRS(output.projection)writePointsShape(tmp.df,paste0(name,"BBMM_points"),factor2char=TRUE)cat(showWKT(proj4string(newlist[[1]])),file=paste0(name,"BBMM_points.prj"))}rm(grid,infile,tmp.xy,BBMM,BottomY,cell.size,contours,i,LeftX,levels,loc.error,maxlag,name,out.raster,raster.contour,RightX,size,tmp.df,TopY,X,x,xcoords,Y,y,ycoords,z)#removeunwantedobjects
53
APPENDIXBGPS_ANo,GMT.Date,GMT.Time,Latitude,Longitude1,04.03.2014,17:17:06,27.5196477,-97.88165082,24.03.2015,18:00:54,26.6064405,-97.52665663,25.03.2015,6:01:48,26.5989913,-97.52292844,26.03.2015,6:02:00,26.5978741,-97.52855235,27.03.2015,6:01:29,26.5984423,-97.52536756,27.03.2015,18:00:48,26.6059578,-97.52768657,28.03.2015,6:01:54,26.5984083,-97.52187328,29.03.2015,6:01:49,26.604351,-97.52824829,30.03.2015,6:01:50,26.6054602,-97.527620410,31.03.2015,6:01:29,26.6094811,-97.522140811,31.03.2015,18:03:01,26.606822,-97.526541112,01.04.2015,6:01:48,26.611661,-97.517301613,02.04.2015,6:02:30,26.5985723,-97.531717914,03.07.2015,4:31:00,26.6052205,-97.524490315,03.07.2015,5:00:29,26.6052209,-97.524412616,03.07.2015,5:30:19,26.605227,-97.524449817,03.07.2015,6:01:13,26.6052318,-97.524509518,04.07.2015,6:01:29,26.598013,-97.531743419,05.07.2015,6:03:35,26.5981892,-97.532310520,06.07.2015,6:01:29,26.5979925,-97.532362421,07.07.2015,6:02:00,26.5992063,-97.534187522,07.07.2015,18:01:30,26.6117546,-97.517434423,08.07.2015,6:01:53,26.5992264,-97.522076424,09.07.2015,6:01:29,26.6075099,-97.520876125,10.07.2015,6:01:29,26.6021617,-97.521233326,10.07.2015,18:02:00,26.607033,-97.51949527,11.07.2015,18:02:00,26.595673,-97.520913628,12.07.2015,18:01:18,26.6065042,-97.519929429,13.07.2015,6:01:29,26.5988166,-97.531222930,13.07.2015,18:02:41,26.607097,-97.520651531,14.07.2015,6:01:47,26.6120814,-97.518216532,14.07.2015,18:01:00,26.5986079,-97.5318048
54
GPS_BNo,GMT.Date,GMT.Time,Latitude,Longitude1,20.03.2015,15:34:02,26.4821409,-97.7487362,04.05.2015,9:31:00,26.604591,-97.50158353,04.05.2015,10:01:10,26.6046073,-97.50157834,04.05.2015,10:30:34,26.604535,-97.50164665,04.05.2015,11:00:50,26.6046899,-97.50177666,04.05.2015,11:31:09,26.6051792,-97.50201297,04.05.2015,12:01:00,26.604178,-97.50251878,04.05.2015,12:30:51,26.6041361,-97.5013219,04.05.2015,13:02:54,26.6046071,-97.501588810,04.05.2015,13:30:38,26.6045807,-97.501631211,04.05.2015,14:00:24,26.6044976,-97.501667912,04.05.2015,14:30:11,26.6045028,-97.501641413,04.05.2015,15:00:30,26.6045482,-97.501625414,04.05.2015,15:30:44,26.6045768,-97.50162215,04.05.2015,16:00:21,26.6045811,-97.501623916,04.05.2015,16:32:01,26.6045905,-97.501469217,05.05.2015,3:30:26,26.6054723,-97.504025518,05.05.2015,4:02:04,26.6059761,-97.504210219,05.05.2015,4:32:06,26.6049197,-97.505794320,18.05.2015,12:31:57,26.6039967,-97.501319921,18.05.2015,13:01:20,26.6040002,-97.501520922,19.05.2015,0:00:10,26.6046622,-97.50199323,19.05.2015,0:32:34,26.6052456,-97.501969924,19.05.2015,1:01:24,26.606089,-97.502933825,19.05.2015,1:31:00,26.6068372,-97.502699626,19.05.2015,2:00:26,26.6071276,-97.502409427,03.06.2015,2:31:27,26.6039387,-97.50129328,03.06.2015,3:00:29,26.6048106,-97.499938729,03.06.2015,3:31:00,26.6065412,-97.500018130,03.06.2015,4:00:13,26.6080513,-97.499903431,03.06.2015,4:30:20,26.6088912,-97.500164732,03.06.2015,5:00:30,26.6088553,-97.500069333,03.06.2015,5:30:23,26.609892,-97.49995934,03.06.2015,6:03:00,26.6096874,-97.499320135,04.06.2015,6:02:49,26.6077894,-97.500268636,06.06.2015,6:01:30,26.6096849,-97.49990437,06.06.2015,18:01:48,26.605011,-97.502679138,25.06.2015,6:01:59,26.6107375,-97.490877339,27.06.2015,6:02:40,26.6128831,-97.494368840,28.06.2015,18:00:54,26.6127302,-97.494120241,01.07.2015,6:02:17,26.6146628,-97.487576742,01.07.2015,18:00:29,26.6149471,-97.490636643,10.07.2015,6:03:00,26.6138451,-97.489209144,11.07.2015,18:01:30,26.6150099,-97.4904467
55
GPS_CNo,GMT.Date,GMT.Time,Latitude,Longitude1,20.04.2015,14:33:29,26.4819699,-97.76495512,20.04.2015,15:00:16,26.5722701,-97.44824993,03.05.2015,6:02:31,26.6183978,-97.4820384,04.05.2015,6:01:24,26.6184227,-97.4819475,04.05.2015,6:30:25,26.618533,-97.48203446,04.05.2015,7:00:16,26.6184642,-97.48169687,04.05.2015,19:30:15,26.6107478,-97.50967678,04.05.2015,20:01:24,26.6107796,-97.50977089,04.05.2015,20:30:15,26.6106074,-97.509809510,04.05.2015,21:00:36,26.6107062,-97.509238111,04.05.2015,21:30:30,26.6107829,-97.509917112,04.05.2015,22:01:30,26.6107491,-97.509800813,04.05.2015,22:30:17,26.6107645,-97.509840214,04.05.2015,23:00:19,26.6107744,-97.509794615,04.05.2015,23:30:15,26.6108339,-97.509899916,05.05.2015,0:01:31,26.6108225,-97.509709917,10.05.2015,18:02:48,26.604987,-97.499665718,11.05.2015,6:01:47,26.6120679,-97.501946519,12.05.2015,6:02:31,26.6195127,-97.499544920,12.05.2015,18:01:01,26.6108786,-97.501274521,13.05.2015,18:01:18,26.6055012,-97.494499422,14.05.2015,6:01:59,26.6132533,-97.494784623,31.05.2015,6:02:30,26.6109213,-97.500229424,01.06.2015,18:01:57,26.6015498,-97.493520225,02.06.2015,6:02:25,26.6353387,-97.489361426,02.06.2015,6:30:22,26.6326484,-97.485393827,02.06.2015,7:00:25,26.6326469,-97.479634828,02.06.2015,7:30:54,26.6293693,-97.476744229,01.07.2015,6:03:14,26.6165646,-97.49378930,01.07.2015,18:01:45,26.6114574,-97.490175431,02.07.2015,6:00:29,26.5997675,-97.493121132,02.07.2015,6:01:08,26.5997256,-97.492993833,02.07.2015,6:30:16,26.5985585,-97.490966634,02.07.2015,7:00:13,26.5953412,-97.487556835,02.07.2015,7:30:14,26.592486,-97.482647436,02.07.2015,8:00:59,26.5915851,-97.480761437,02.07.2015,8:32:32,26.5905198,-97.480130238,02.07.2015,9:01:59,26.5940041,-97.480370539,02.07.2015,9:31:24,26.5993019,-97.48195940,12.07.2015,18:01:54,26.6117236,-97.500273241,13.07.2015,6:01:47,26.6040232,-97.501616542,14.07.2015,18:02:47,26.6038701,-97.501221243,15.07.2015,6:01:55,26.6185324,-97.481871
56
GPS_DNo,GMT.Date,GMT.Time,Latitude,Longitude1,04.04.2015,6:01:30,26.6091494,-97.51883752,04.04.2015,6:30:17,26.609306,-97.51917113,04.04.2015,7:00:19,26.6093546,-97.5192314,04.04.2015,7:30:17,26.6098715,-97.51965495,04.04.2015,8:00:54,26.6099107,-97.51966636,04.04.2015,8:30:15,26.6103555,-97.52134887,04.04.2015,9:00:15,26.6110596,-97.52187848,04.04.2015,9:30:32,26.6110683,-97.52186329,04.04.2015,10:00:14,26.6097845,-97.524973810,04.04.2015,10:30:23,26.6063357,-97.527033511,04.04.2015,11:00:20,26.6001222,-97.531290712,04.04.2015,11:30:13,26.5980463,-97.530655313,04.04.2015,12:00:14,26.5967446,-97.529734514,04.04.2015,12:30:14,26.5965947,-97.529197915,04.04.2015,13:00:49,26.5975529,-97.527587216,04.04.2015,13:30:18,26.5975422,-97.52763717,04.04.2015,14:00:12,26.5983114,-97.526774118,04.04.2015,14:30:14,26.5988762,-97.524421219,04.04.2015,15:00:30,26.5998497,-97.523061220,04.04.2015,15:30:51,26.5987122,-97.521857821,04.04.2015,16:00:30,26.5987009,-97.521917522,04.04.2015,16:30:20,26.5987193,-97.521872423,04.04.2015,17:00:13,26.598694,-97.521892324,04.04.2015,17:30:24,26.5987688,-97.521939325,04.04.2015,18:00:19,26.598785,-97.521936626,04.04.2015,18:30:10,26.5981288,-97.520961827,04.04.2015,19:00:13,26.6002612,-97.520694528,04.04.2015,19:30:26,26.6003189,-97.520680429,04.04.2015,20:00:17,26.6007169,-97.521793530,04.04.2015,20:31:26,26.6027113,-97.521392131,04.04.2015,21:01:20,26.6030987,-97.521872232,04.04.2015,21:30:55,26.6030413,-97.521900533,04.04.2015,22:00:55,26.6030844,-97.521902234,04.04.2015,22:30:38,26.6030525,-97.521827135,04.04.2015,23:00:55,26.6030589,-97.521845936,04.04.2015,23:31:16,26.6032073,-97.5217183
57
GPS_ENo,GMT.Date,GMT.Time,Latitude,Longitude1,18.04.2015,6:00:52,26.6000133,-97.53123272,18.04.2015,6:30:28,26.6000196,-97.53111333,18.04.2015,7:00:14,26.5999368,-97.53106894,18.04.2015,7:30:15,26.5998814,-97.53103275,18.04.2015,8:00:22,26.5999176,-97.53103926,18.04.2015,8:30:37,26.5999812,-97.53106767,18.04.2015,9:00:05,26.5999377,-97.53097288,18.04.2015,9:30:26,26.5999868,-97.53103919,18.04.2015,10:00:30,26.5997678,-97.530597910,18.04.2015,10:30:21,26.5998276,-97.530459911,18.04.2015,11:00:21,26.5997476,-97.530059912,18.04.2015,11:30:19,26.5997161,-97.53004213,18.04.2015,12:00:54,26.5997281,-97.53004614,18.04.2015,12:30:18,26.5997968,-97.529814415,18.04.2015,13:00:27,26.599798,-97.529786616,18.04.2015,13:30:35,26.5998599,-97.529768617,18.04.2015,14:00:57,26.599702,-97.529836618,18.04.2015,14:31:47,26.5998226,-97.529787219,18.04.2015,15:00:30,26.5999551,-97.529730720,18.04.2015,15:30:26,26.5996671,-97.529292921,18.04.2015,16:01:20,26.599604,-97.52925222,18.04.2015,16:32:00,26.5996832,-97.529292923,18.04.2015,17:02:03,26.5996427,-97.529284524,18.04.2015,17:32:17,26.5996721,-97.529263225,18.04.2015,18:01:48,26.5996494,-97.529222326,18.04.2015,18:30:27,26.5996164,-97.529253827,18.04.2015,19:00:29,26.5995333,-97.529208928,18.04.2015,19:30:56,26.5994689,-97.529198429,18.04.2015,20:00:48,26.5995661,-97.529210130,18.04.2015,20:30:49,26.5994364,-97.529222731,18.04.2015,21:00:30,26.599468,-97.529172732,18.04.2015,21:30:32,26.599511,-97.529019833,18.04.2015,22:00:31,26.5994915,-97.529090134,18.04.2015,22:30:20,26.5994762,-97.528993935,18.04.2015,23:00:07,26.599465,-97.528896536,18.04.2015,23:30:20,26.5995674,-97.529025137,19.04.2015,0:00:19,26.5995419,-97.529044438,19.04.2015,0:30:13,26.5996365,-97.528411939,19.04.2015,1:00:14,26.5995811,-97.528389440,19.04.2015,1:30:15,26.5995823,-97.528361641,19.04.2015,2:00:18,26.5995214,-97.528367642,19.04.2015,2:30:45,26.5995531,-97.528307143,19.04.2015,3:00:06,26.5994356,-97.528231644,19.04.2015,3:30:30,26.5994335,-97.528271545,19.04.2015,4:00:12,26.5994684,-97.528305846,19.04.2015,4:30:13,26.5994157,-97.5283039