Dummy SpatialPolygon:
x_coord <- c(16.48438, 17.49512, 24.74609, 22.59277, 16.48438)
y_coord <- c(59.736328125, 55.1220703125, 55.0341796875, 61.142578125, 59.736328125)
xym <- cbind(x_coord, y_coord)
library(sp)
p = Polygon(xym)
ps = Polygons(list(p),1)
sps = SpatialPolygons(list(ps))
plot(sps)
Dummy dataframe:
df <- data.frame (date= c("2021", "2015", "2018"),
value= c(100, 147, 25))
Basic question but how can I add the columns names of the dataframe to the spatial polygon ? (I don't need to add some value, I just want my spatialpolygon to have the field "date" and "value")
You can extend your object (Spatial Polygons in this case) with addAttrToGeom
library(sp)
spsCRS <- CRS(SRS_string = "EPSG:4326")
p = Polygon(xym)
ps = Polygons(list(p),1)
sps = SpatialPolygons(list(ps))
proj4string(sps) <- spsCRS
plot(sps)
df <- data.frame("ID" = 1, "Name" = "MyNewPolygon", "URL" = "http://example.org")
spsDf <- addAttrToGeom(sps, df, match.ID = "ID")
Which creates a new object:
An object of class "SpatialPolygonsDataFrame"
Slot "data":
ID Name URL
1 1 MyNewPolygon http://example.org
Slot "polygons":
[[1]]
[...]