Reputation: 645
I'm trying to become more R savvy by moving away from loops and towards apply statements. I have a list of data frames and I would like my output to be a list of data frames as well, so lapply sounds like it's the right one. The code below (temperamentally) works and uses the geodist() function from the gmt package to find the distance in meters between a lat and long in a row and the lat and long that comes in the row before it. The problem is I don't know how to call the row before in a vectorized function (below I am using j-1). I don't think this should be too difficult but I'm relatively new to vectors. I've read through many of the posts and documentation on apply and lapply but am not quite getting it.
sample data:
lat <- c(32.87707, 32.87708, 32.87694, 32.87726, 32.87469)
lon <- c(-117.2386, -117.2334, -117.2378, -117.2356, -117.2329)
coords <- data.frame(cbind(lat, lon))
conList <- list(coords, coords, coords, coords)
tripDists <- list()
for (i in 1:length(conList)) {
for (j in 2:nrow(conList[[i]])) {
tripDists[[i]][j] <- geodist(conList[[i]][j,"lat"], conList[[i]][j,"lon"], conList[[i]]$lat[j-1], conList[[i]]$lon[j-1], units="km")*1000
}
}
In pseudo code something like:
lapply(conList, geodist(x,y,m,z, units="km"), m= x-1, z=y-1)
Upvotes: 1
Views: 194
Reputation: 12819
Try this instead:
tripDists <- lapply(conList, with, {
geodist(tail(lat,-1), tail(lon,-1), head(lat,-1), head(lon,-1), units="km")*1000
})
Upvotes: 2