Skip to content
Prev 26830 / 29559 Next

help: Problem getting centroids inside lists

Maybe the following function is what you're looking for?

getcentroids <- function(x1) {
  getcentroid <- function(x) {
    coords <- slot(x, "coords")
    numrows <- dim(coords)[1]
    ret <- if(numrows == 2) {
      matrix(apply(coords,2,mean), nrow=1)
    } else {
      if(numrows == 1) {
        coords
      } else {
        geosphere::centroid(coords)
      }
    }
    ret
  }

  r <- lapply(x1, function(x) as.data.frame(getcentroid(x)))

  ret <- matrix(unlist(r), ncol=2, byrow=TRUE)
  rownames(ret) <- names(r); colnames(ret) <- c("lon", "lat")

  ret
}

Now call it as lapply(ct, getcentroids)

HTH,
Vijay.

On Wed, Sep 12, 2018 at 2:42 PM Ariel Fuentesdi <ariel.fuentesdi at usach.cl>
wrote: