Skip to content
Prev 26829 / 29559 Next

help: Problem getting centroids inside lists

I went to a more general approach, that is:

ctply <- lapply(X = s, FUN = function(x) sapply(X = ct[[x]],
          FUN = function(y) if(length(y)>1) geosphere::centroid(slot(y,
"coords"))
          else sp::coordinates(slot(y, "coords"))))

But now I want to add the case when they are only two elements. The dataset
will be:

ct <- list(a = list(one = data.frame(lon = c(-180, -160, -60), lat = c(-20,
5, 0)),
                    two = data.frame(lon = c(-18, -16), lat = c(-2, 50))),
           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

And I did the following but it doesn't work:

ctply <- lapply(X = s, FUN = function(x) sapply(X = ct[[x]],
                                                FUN = function(y)
if(length(y)>2) geosphere::centroid(slot(y, "coords"))
                                                else if (length(y) == 1)
sp::coordinates(slot(y, "coords"))
                                                else
mean(sp::coordinates(slot(y, "coords")))))

I need the result of each element of the list will be a matrix of two rows
per column (named: one, two). How do I fix it?

Regards,
Ariel

2018-09-10 17:29 GMT-03:00 MacQueen, Don <macqueen1 at llnl.gov>: