fmatos - 1 year ago 70

R Question

I want to extract from the online database OBIS all the species occurrence records for a group of polygons. The number of polygons is to large to get all of them at the same time so I thought to use a loop to achieve it. The problem I'm facing is due the fact that not all polygons have records so the result is an empty dataframe and the loop stops. I tried to use the control-flow "if" but is not working. Can I get what I need with a loop? Here is a shorter version of the shapefile I'm using.

`library(robis)`

library(maptools)

library(mregions)

library(plyr)

polygons <- readShapeSpatial("~/smaller.shp")

occurrence_list = list()

for (i in 1:length(polygons)){

wkt_polygons <- mr_as_wkt(polygons[i,])

occur <- occurrence(geometry=wkt_polygons)

if(is.null(occur) next

occur$i<-i

occurrence_list[[i]] <- occur

}

data <- dplyr::bind_rows(occurrence_list)

Answer Source

I'm not sure how the required result should look like, but this might work:

```
occurrence_list = list()
for (i in 1:length(polygons)){
wkt_polygons <- mr_as_wkt(polygons[i,])
occur <- occurrence(geometry=wkt_polygons)
if(nrow(occur) > 0) {
occur$i<-i
occurrence_list[[length(occurrence_list) + 1]] <- occur
}
}
data <- dplyr::bind_rows(occurrence_list)
```