导出 SpatialPointsDataFrame 的子集
Exporting a subset of a SpatialPointsDataFrame
我使用以下代码创建了一个 SpatialPointsDataFrame
:
SpatialPointsDataFrame(coords = xy, data = data4xy,
proj4string = CRS("+proj=utm +zone=9 ellps=WGS84"))
其中 data4xy
是一个包含 2 列的数据框,date
是与每个 GPS 点关联的时间戳,id
是被跟踪动物的 ID。
从这个 SpatialPointsDataFrame
,我想使用 writeOGR()
为每只被追踪的动物导出一个 shapefile(基本上按 id
分组)。我将如何实施它?
只需在 for
循环或 *apply 语句中使用 subset
,例如:
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")
})
我使用以下代码创建了一个 SpatialPointsDataFrame
:
SpatialPointsDataFrame(coords = xy, data = data4xy,
proj4string = CRS("+proj=utm +zone=9 ellps=WGS84"))
其中 data4xy
是一个包含 2 列的数据框,date
是与每个 GPS 点关联的时间戳,id
是被跟踪动物的 ID。
从这个 SpatialPointsDataFrame
,我想使用 writeOGR()
为每只被追踪的动物导出一个 shapefile(基本上按 id
分组)。我将如何实施它?
只需在 for
循环或 *apply 语句中使用 subset
,例如:
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")
})