I have been trying to create an empty SpatialPoints in R but have not found the way yet.
I have tried with this formula:
SpatialPoints(as.matrix(data.table(x = numeric(), y = numeric())))
But it didn't work. The closest thing I have found on the internet is Creating empty Polygons or SpatialPolygons in R? but that is for polygons and apparently it does not work the same way.
I have sp version 1.2.7
2 Answers 2
Create a SpatialPoints
object with one row in it, and then drop it with [-1,]
:
> zero = SpatialPoints(data.frame(x = 0, y = 0))[-1,]
> zero
SpatialPoints:
x y
Coordinate Reference System (CRS) arguments: NA
Quick test to see what this thing is:
> length(zero)
[1] 0
> class(zero)
[1] "SpatialPoints"
attr(,"package")
[1] "sp"
-
[temp_comment] by chance I found a duplicate account of yours (gis.stackexchange.com/users/3537/spacedman?tab=profile). Is it on purpose? If you are interested, you can merge them (gis.stackexchange.com/help/merging-accounts).Andre Silva– Andre Silva2019年02月09日 01:27:27 +00:00Commented Feb 9, 2019 at 1:27
Maybe there is a shorter way ...
new("SpatialPoints",
coords = structure(numeric(0), .Dim = c(0L, 2L),
.Dimnames = list(NULL, c("coords.x1", "coords.x2"))),
bbox = structure(c(1, 1, 1, 1), .Dim = c(2L, 2L),
.Dimnames = list(c("coords.x1", "coords.x2"),
c("min", "max"))),
proj4string = new("CRS", projargs = NA_character_))
# SpatialPoints:
# coords.x1 coords.x2
# Coordinate Reference System (CRS) arguments: NA
for
loop to incrementally add points to, you might be better off using anapply
-type operation and then combining the results in the end - this is usually faster than growing a vector from an empty object.