(This article was first published on me nugget, and kindly contributed to R-bloggers)
Here are some functions that I regularly use for geographic data (e.g. binning, filtering, calculation of new positions etc.).
#distance in kilometers between two long/lat positions (from "fossil" package)
earth.dist <- function (long1, lat1, long2, lat2)
{
rad <- pi/180
a1 <- lat1 * rad
a2 <- long1 * rad
b1 <- lat2 * rad
b2 <- long2 * rad
dlon <- b2 - a2
dlat <- b1 - a1
a <- (sin(dlat/2))^2 + cos(a1) * cos(b1) * (sin(dlon/2))^2
c <- 2 * atan2(sqrt(a), sqrt(1 - a))
R <- 6378.145
d <- R * c
return(d)
}
#degree bearing between two long/lat positions (from "fossil" package)
earth.bear <- function (long1, lat1, long2, lat2)
{
rad <- pi/180
a1 <- lat1 * rad
a2 <- long1 * rad
b1 <- lat2 * rad
b2 <- long2 * rad
dlon <- b2 - a2
bear <- atan2(sin(dlon) * cos(b1), cos(a1) * sin(b1) - sin(a1) *
cos(b1) * cos(dlon))
deg <- (bear%%(2 * pi)) * (180/pi)
return(deg)
}
new.lon.lat <-
function (lon, lat, bearing, distance)
{
rad <- pi/180
a1 <- lat * rad
a2 <- lon * rad
tc <- bearing * rad
d <- distance/6378.145
nlat <- asin(sin(a1) * cos(d) + cos(a1) * sin(d) * cos(tc))
dlon <- atan2(sin(tc) * sin(d) * cos(a1), cos(d) - sin(a1) *
sin(nlat))
nlon <- ((a2 + dlon + pi)%%(2 * pi)) - pi
npts <- cbind(nlon/rad, nlat/rad)
return(npts)
}
#tells which lon lat positions are within the defined limits to the west, east, north, and south
lon.lat.filter <-
function (lon_vector, lat_vector, west, east, north, south)
{
if(west>east) {
lon_vector_new=replace(lon_vector, which(lon_vector<0), lon_vector[which(lon_vector<0)]+360)
east_new=east+360
} else {
lon_vector_new=lon_vector
east_new=east
}
hits=which(lon_vector_new < east_new & lon_vector_new > west & lat_vector < north & lat_vector > south)
return(hits)
}
To leave a comment for the author, please follow the link and comment on his blog: me nugget.
R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series,ecdf, trading) and more...

Zero Inflated Models and Generalized Linear Mixed Models with R.
Zuur, Saveliev, Ieno (2012).