I want to extract a shapefile value at a particular location. The shapefile I am using is can be found here, downloaded by clicking Download IHO Sea Areas
. The shape file contains all the possible seas.
I can read it and plot it using:
require("maptools")
require(rgdal)
require(sp)
ogrListLayers("World_Seas.shp")
shape <- readOGR("World_Seas.shp", layer="World_Seas")
However, I would like to extract the sea value for a particular location, say
p <- c(-20, 40)
there is a probably an easier way but here is my take
require("maptools")
require(rgdal)
require(sp)
library(plyr)
library(dplyr)
setwd("/Users/drisk/Downloads/seas")
ogrListLayers("World_Seas.shp")
shape=readOGR("World_Seas.shp", layer="World_Seas")
datapol <- data.frame(shape)
pointtoplot <- data.frame(x=-20, y=40)
coordinates(pointtoplot) <- ~ x + y
proj4string(pointtoplot) <- CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
#
#function over from package sp
test <- data.frame(xx=over(shape, pointtoplot))
combine <- cbind(test, datapol)
combine <- na.omit(combine) #only one point left
output for your point x=-20, y=40
xx NAME ID Gazetteer_ id
35 1 North Atlantic Ocean 23 1912 35
You could use the over
function from the sp
package:
library(rgdal)
library(sp)
library(raster)
shape <- shapefile("~/tmp/World_Seas.shp")
head(shape)
plot(shape[shape$ID == 35, ], axes = TRUE)
points(pts)
pts <- SpatialPoints(cbind(-20, 40),
proj4string = CRS(proj4string(shape)))
over(pts, shape)
or even shorter:
pts %over% shape
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With