Slav - 2 months ago 6

R Question

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

i<-i+1

}

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.

EDIT:

I resolved the issue - using function

`tail()`

Answer

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)
local.map = map(database = "state", fill = TRUE, plot = FALSE)
IDs = sapply(strsplit(local.map$names, ":"), function(x) x[1])
states = map2SpatialPolygons(map = local.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)
NROW(states@polygons[[i]]@Polygons[[1]]@coords)))
simple.states = states[which(lengths < 200)]
plot(simple.states)
```