简体   繁体   中英

How to add columns names to a spatialpolygon based on column from a dataframe?

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]]
[...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM