0

I have a Large SpatialPolygonsDataFrame downloaded from here:

http://omap.africanmarineatlas.org/BIOSPHERE/pages/3_terrestrial%20vegetation.htm

I used the following to create the SpatialPolygonsDataFrame:

white_veg <- readOGR(dsn="data", 
                     layer="Whites vegetation")

I have a separate dataframe that looks like this:

id <- c(1,2,3,4,5,6,7,8)
lat <- c(13.8, 13.552, 13.381, -15.440, -15.860, 13.967, -27.750, -27.750)
lon <- c(2.250, 2.687, 2.865, 23.250, 23.340, 30.527, 21.420, 21.420)
x <- c(566, 537, 554, 879, 811, 268, 216, 216)
y <- c(8, 10.32, 3.83, 64.8, 53.7, 4, 5.8, 2.2)

locations <- data.frame(id, lat, lon, x, y)

I want to create a new column in locations that classifies each row according to which vegetation type polygon from white_veg the lat+lon coordinates are inside, e.g. the factors in white_veg@data$DESCRIPTIO.

I have read a question on gcontains() from the rgeos package, but this only returns a logical vector of length 1, I'm not sure what that indicates:

locations_coords <- data.frame(locations$lat, locations$lon)
locations_spoints <- SpatialPoints(locations_coords,proj4string=CRS(proj4string(white_veg)))
gContains(white_veg, locations_spoints)

I also looked at this on the GIS SE, using over from the sp package, but the answers weren't thorough enough for me to understand.

John L. Godlee
  • 559
  • 5
  • 21

1 Answers1

0

I ended up using over from the sp package like this:

locations_veg_class <- locations %>% 
mutate(veg_class = over(locations_spoints, white_veg)$DESCRIPTIO)

where locations_spoints is the SpatialPoints object I created in the question.

John L. Godlee
  • 559
  • 5
  • 21
  • Having used the method above and investigated it properly, I've found that `over()` isn't classifying the data points properly. Most are coming out as NA, but I know from plotting them that they do occur inside one of my polygons. Any ideas what I've done wrong? – John L. Godlee Oct 10 '17 at 12:18