[R-sig-Geo] help: Problem getting centroids inside lists

Ariel Fuentesdi @riel@fuente@di @ending from u@@ch@cl
Mon Sep 10 19:56:49 CEST 2018


Hi everyone,

I have a list of coordinates called "ct" and I want to extract the
centroids of each sublist, but it only works when it has only 3 or more
points. In ct$b$two only has one point; in that case, I would rescue that
point as If it were a centroid.

This is what I did:

library(dplyr)
library(geosphere)

ct <- list(a = list(one = data.frame(lon = c(-180, -160, -60), lat = c(-20,
5, 0)),
                    two = data.frame(lon = c(-18, -16, -6), lat = c(-2, 50,
10))),
           b = list(one = data.frame(lon = c(-9, -8, -3), lat = c(-1, 25,
5)),
                    two = data.frame(lon = c(-90), lat = c(-1))))

coordinates(ct$a$one) <- ~lon+lat
coordinates(ct$a$two) <- ~lon+lat
coordinates(ct$b$one) <- ~lon+lat
coordinates(ct$b$two) <- ~lon+lat

s <- 1:length(ct)
ctply <- list()
for (i in s){
 for (j in 1:length(ct[[i]])) {
  ctply[[i]][j] <- ifelse(test = lengths(ct[[i]][1]) > 2, yes = sapply(X =
ct[[i]][j],
    FUN = function(y) geosphere::centroid(slot(y, "coords"))), no =
ct[[i]][j] )
 }
}

Thanks in advance

Regards,
Ariel

	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list