Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract shapefile value to point with R

Tags:

r

gis

rgdal

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)
like image 754
user3910073 Avatar asked Dec 14 '15 16:12

user3910073


2 Answers

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
like image 111
MLavoie Avatar answered Nov 14 '22 23:11

MLavoie


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
like image 26
johannes Avatar answered Nov 14 '22 23:11

johannes