简体   繁体   中英

Accessing the row before using lapply in R for a list of data frames

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)

Try this instead:

tripDists <- lapply(conList, with, {
    geodist(tail(lat,-1), tail(lon,-1), head(lat,-1), head(lon,-1), units="km")*1000
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM