Splash1199 Splash1199 - 3 months ago 21
R Question

Exporting a subset of a SpatialPointsDataFrame

I have created a

SpatialPointsDataFrame
using the following code:

SpatialPointsDataFrame(coords = xy, data = data4xy,
proj4string = CRS("+proj=utm +zone=9 ellps=WGS84"))


where
data4xy
is a data frame containing 2 columns,
date
is the time stamp associated with each GPS point and
id
is the id of the tracked animal.

From this
SpatialPointsDataFrame
, I would like to export a shapefile using
writeOGR()
for each tracked animal (essentially grouping by
id
). How would I go about implementing this?

rcs rcs
Answer

Just use subset in a for loop or an *apply statement, e.g.:

library("sp")
library("rgdal")

data("meuse")  # example data
coordinates(meuse) <- ~x+y
proj4string(meuse) <- CRS("+init=epsg:28992")

# separate by `soil`
table(meuse$soil)
#  1  2  3 
# 97 46 12 

id_list <- levels(meuse$soil)  # `levels()` for factors, otherwise `unique()`

# subset SpatialPointsDataFrame and write shapefiles
lapply(id_list,
       function(x) { 
         writeOGR(obj=subset(meuse, soil==x), dsn=".",
                  layer=sprintf("meuse_%s", x),
                  driver="ESRI Shapefile")
       })
Comments