Slav Slav - 5 months ago 17
R Question

R function to count coordinates

Trying to get it done via mapply or something like this without iterations - I have a spatial dataframe in R and would like to subset all more complicated shapes - ie shapes with 10 or more coordinates. The shapefile is substantial (10k shapes) and the method that is fine for a small sample is very slow for a big one. The iterative method is

Street$cc <-0
i <- 1
while(i <= nrow(Street)){
Street$cc[i] <-length(coordinates(Street)[[i]][[1]])/2

How can i get the same effect in any array way? I have a problem with accessing few levels down from the top (Shapefile/lines/Lines/coords)

I tried:

Street$cc <- lapply(slot(Street, "lines"),
function(x) lapply(slot(x, "Lines"),
function(y) length(slot(y, "coords"))/2))

/division by 2 as each coordinate is a pair of 2 values/
but is still returns a list with number of items per row, not the integer telling me how many items are there. How can i get the number of coordinates per each shape in a spatial dataframe? Sorry I do not have a reproducible example but you can check on any spatial file - it is more about accessing low level property rather than a very specific issue.

I resolved the issue - using function


dww dww

Here is a reproducible example. Slightly different to yours, because you did not provide data, but the principle is the same

First lets get a spatial ploygon. I'll use the US state boundaries;

library(maps) = map(database = "state", fill = TRUE, plot = FALSE) 
IDs = sapply(strsplit($names, ":"), function(x) x[1])
states = map2SpatialPolygons(map =, ID = IDs) 

Now we can subset the polygons with fewer than 200 vertices like this:

# Note: next line assumes that only interested in one Polygon per top level polygon.
# I.e. assumes that we have only single part polygons
# If you need to extend this to work with multipart polygons, it will be
# necessary to also loop over values of lower level Polygons
lengths = unlist(sapply(1:length(states), function(i) 

simple.states = states[which(lengths < 200)]

enter image description here