Convert SpatialPoints to SpatialPointsDataFrame
Given x
a SpatialPoints
object:
> x
class : SpatialPoints
features : 50
extent : 0.0006317429, 0.9926516, 0.02675848, 0.9901886 (xmin, xmax, ymin, ymax)
coord. ref. : +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
...you can convert to SpatialPointsDataFrame
with as
:
> as(x,"SpatialPointsDataFrame")
class : SpatialPointsDataFrame
features : 50
extent : 0.0006317429, 0.9926516, 0.02675848, 0.9901886 (xmin, xmax, ymin, ymax)
coord. ref. : +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
variables : 0
>
but note that gives you a SpatialDataFrame with 50 points but seemingly no rows or columns and any attempt to assign 50 data values will fail:
> dim(xs)
[1] 0 0
> xs$ID=1:50
Error in `[[<-.data.frame`(`*tmp*`, name, value = 1:50) :
replacement has 50 rows, data has 0
[Edit: after trying to track down the code that does this in sp
I discovered that this coercing method is introduced by attaching the raster
package - otherwise you get an immediate error...]
You can fix this by assigning to the @data
slot with a data frame of the right number of rows:
> xs@data = data.frame(ID=1:50)
> xs
class : SpatialPointsDataFrame
features : 50
extent : 0.0006317429, 0.9926516, 0.02675848, 0.9901886 (xmin, xmax, ymin, ymax)
coord. ref. : +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
variables : 1
names : ID
min values : 1
max values : 50
and then you can add columns as normal for a data frame:
> xs$ZZZ = runif(50)
>
Alternatively if you have a data frame you want to put on the points at construction time, use the SpatialPointsDataFrame
constructor with points and data:
> xs = SpatialPointsDataFrame(x, data.frame(ID=1:50,ZZZ=runif(50)))
> xs
class : SpatialPointsDataFrame
features : 50
extent : 0.0006317429, 0.9926516, 0.02675848, 0.9901886 (xmin, xmax, ymin, ymax)
coord. ref. : +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
variables : 2
names : ID, ZZZ
min values : 1, 0.0235063806176186
max values : 50, 0.983690821100026
>
Use SpatialPointsDataFrame
with data.frame
to coerce into the desired object.
library(sp)
x <- SpatialPoints( rbind(c(1.5, 2), c(2.5, 2), c(0.5, 0.5), c(1, 0.25),
c(1.5, 0), c(2, 0), c(2.5, 0), c(3, 0.25),
c(3.5, 0.5)))
class(x)
Here we create a data.frame
within the call to SpatialPointsDataFrame
that contains a sequential ID column based on the number of points. This could be anything as long as the row/column dimensions are correct.
x <- SpatialPointsDataFrame(x, data.frame(ID=1:length(x)))
class(x)