User Tools

Site Tools


r:r-gis:vector

2-Vector Operations

open a shapefile

  #Polygons:
  shapeLayer=readShapePoly("shapeLayer.shp")
  #Points:
  shapeLayer=readShapePoints("shapeLayer.shp")
  #oder vector files in general using rgdal:
  readOGR(shapeFile, layer)

We advice to use readOGR because it ensures that all raster information (e.g projections) are read.

Spatial Layer from data.frame

#e.g. for points (in latlong)
SpatialPointsDataFrame(data.frame(X,Y),
                                data.frame(Z),
                                proj4string = CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
                       )

Define/Assign projection

EPSG codes and proj4 strings can be found on http://spatialreference.org/

  # with an proj4 string
  proj4string(shapeLayer) <- CRS("+proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")
  # or with an EPSG code (in this case the code for MGI West)
  proj4string(shapeLayer) <- CRS("+init=epsg:31254")

Project vector

  newproj="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
  spTransform(shapeLayer, CRS(newproj))

Subset of Features

  #e.g. the first 2 Features:
  ShapeLayer[1:2,]

Buffer

  #buffer of 10 units (in the geometry of the inputfile)
  gBuffer(SpatialPoints,width=10) 

Append spatial data

bind(Sp1,Sp2)

Statistics on Patches (size, shape, etc)

library(SDMTools)
PatchStat(patches)

Convex hull

A convex hull of a polygon or a point feature set represents the smallest polygon that can be drawn around all features in the set.

gConvexHull(shapeLayer)

Intersect

Either use the gIntersection function from rgeos:

  gIntersection(shapeLayer1,shapeLayer2)

However, if the shapeLayer contains attributes, the intersect function from the raster package is needed:

intersect(shapeLayer1,shapeLayer2)

Polygon contains Features ?

identifys polygonswhich contain specific features (e.g points,polygons,…)

  ghull<-gConvexHull(shapeLayer)
  gIntersection(ghull,Features)

Dissolve

  gUnionCascaded(shapeLayer)

Point Distance

Projection might be either latlon (latlon=TRUE) or metric coordinates(latlon=FALSE)

  #Distance between 2 points:
  pointDistance(SpatialPoint1,SpatialPoint2)
  #or from each point in a layer to a destination:
  pointDistance(SpatialPoints,SpatialPoint1)

To create a point distance matrix use the code above but put it into a loop.

distMatrix<-data.frame()
for (i in 1:length(SpatialPoints)){
distMatrix <- rbind(distMatrix,
  pointDistance(SpatialPoints,SpatialPoints[i,],lonlat=TRUE))
}

Write shapefile to disk

  writeSpatialShape(VectorLayer, "filename.shp")
  #or using rgdal (to keep projection information):
  writeOGR(VectorLayer, outpath, "ShapeName", driver="ESRI Shapefile")

Hanna Meyer

r/r-gis/vector.txt · Last modified: 2018/12/23 19:46 (external edit)