# Distance between two consecutive points where condition applies for both points Is it possible to run through a data.frame and calculate the distance between the points if both point fulfil a condition?

In the enclosed example file i would want to calculate the the distance between two points where values in the actsum column equals or exceeds 0.26.

E.g. the only case where a distance should be calculated is the points in line 6 and 7

Would `pointDistance {raster}` in be usefull for this?

You have at least two common libraries to calculate distance between two geographic points (`sp` and `raster`)

Dummy data:

``````library(sp)
library(raster)

set.seed(123)

df <- data.frame(location.long = rnorm(8, mean = 11.49, sd = 0.0001),
location.lat = rnorm(8, mean = 62.11, sd = 0.0001),
actsum = c(.1,0,1,.03,0,.84,.7,0))
``````

What you want to do is easily achieved through a `for` loop and a logical condition:

With `sp`:

``````results_sp <- numeric(length = dim(df) - 1)

for (i in 1:(dim(df) - 1)) {
if(df[i,'actsum'] >= 0.26 & df[i + 1,'actsum'] >= 0.26){
# results in kilometers (see documentation)
results_sp[i] <- spDists(as.matrix(df[i:(i+1),c('location.long','location.lat')]),
longlat = T, segments = T)
}else{
results_sp[i] <- NA
}
}
``````

With `raster`:

``````results_raster <- numeric(length = dim(df) - 1)

for (i in 1:(dim(df) - 1)) {
if(df[i,'actsum'] >= 0.26 & df[i + 1,'actsum'] >= 0.26){
# results in meters (see documentation)
results_raster[i] <- pointDistance(p1 = df[i,c('location.long','location.lat')],
p2 = df[i + 1,c('location.long','location.lat')],
lonlat = T)
}else{
results_raster[i] <- NA
}
}
``````

Compare results... Are slightly different:

``````rbind(results_sp * 1000, results_raster)

## [,1] [,2] [,3] [,4] [,5]    [,6] [,7]
##  NA   NA   NA   NA   NA 9.90214   NA
##  NA   NA   NA   NA   NA 9.90215   NA
``````