如何根据数据框中的列将列名称添加到空间多边形?
How to add columns names to a spatialpolygon based on column from a dataframe?
虚拟空间多边形:
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)
虚拟数据帧:
df <- data.frame (date= c("2021", "2015", "2018"),
value= c(100, 147, 25))
基本问题,但如何将数据框的列名称添加到空间多边形? (我不需要添加一些值,我只希望我的空间多边形具有字段“日期”和“值”)
您可以使用 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")
创建一个新对象:
An object of class "SpatialPolygonsDataFrame"
Slot "data":
ID Name URL
1 1 MyNewPolygon http://example.org
Slot "polygons":
[[1]]
[...]
虚拟空间多边形:
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)
虚拟数据帧:
df <- data.frame (date= c("2021", "2015", "2018"),
value= c(100, 147, 25))
基本问题,但如何将数据框的列名称添加到空间多边形? (我不需要添加一些值,我只希望我的空间多边形具有字段“日期”和“值”)
您可以使用 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")
创建一个新对象:
An object of class "SpatialPolygonsDataFrame"
Slot "data":
ID Name URL
1 1 MyNewPolygon http://example.org
Slot "polygons":
[[1]]
[...]