-1

I am building a function (for the first time). I am attempting to use earth.dist to calculate the farthest distance between 2 points for each animal-month. I have been fiddling with the codes for about 4 hours and cannot figure out why I am getting identical values for each animal-month (I tested it out on a single animal-month and it worked nicely). Hopefully someone can point me in the correct direction in terms of applying the function to each animal-month. Thanks.

There are essentially 3 columns, animal-month (unique animal ID concatenated with the month), lat and long.

maxdist<- function(latlong, latlongt,a2,dt,farth)
{

latlong<-movementfile[c(18,17)] #cols indicating long/lat

latlongt<-data.table(latlong)

a2<-earth.dist(latlongt, FALSE)

dt<-as.data.frame(as.table(a2))

farth<-max(dt$Freq)
}

lapply(unique(movementfile$animal_month),maxdist)
  • 1
    this question is not clear. please provide data and expected output, see http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Bulat Jun 20 '16 at 22:20
  • It would help if you could include some data using `dput` to make your problem reproducible. – Richard Telford Jun 20 '16 at 22:22
  • Apologies for that - was not aware artificial lat/long data via fdata.lats was available. – ecologist55 Jun 21 '16 at 13:13

1 Answers1

0

How about this:

maxdist<- function(anim_m) 
{
  latlong<-movementfile[movementfile$animal_month==anim_m,c(1,2)] #cols indicating long/lat

  latlongt<-data.table(latlong)

  a2<-earth.dist(latlongt, FALSE)

  dt<-as.data.frame(as.table(a2))

  farth<-max(dt$Freq)
}

#use some data
data(fdata.lats)
movementfile=data.frame(fdata.lats)
movementfile$animal_month=paste(LETTERS[1:(dim(movementfile)[2])],1:(dim(movementfile)[2]),sep="")
movementfile

> movementfile
     longitude latitude animal_month
locA      -109       47           A1
locB      -108       39           B2
locC      -100       44           A1
locD      -117       39           B2
locE       -99       36           A1
locF      -109       43           B2
locG      -113       44           A1
locH      -110       33           B2
locI       -94       40           A1
locJ       -90       45           B2
locK       -94       46           A1
locL      -116       41           B2

lapply(unique(movementfile$animal_month),maxdist)

> unique(movementfile$animal_month)
[1] "A1" "B2"
> lapply(unique(movementfile$animal_month),maxdist)
[[1]]
[1] 1628.118

[[2]]
[1] 2317.066
Robert
  • 5,038
  • 1
  • 25
  • 43