获得S4对象的插槽价值? [英] Getting a slot's value of S4 objects?
本文介绍了获得S4对象的插槽价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我在R中有一个spatialPolygons对象;但我不确定为什么无法从它检索"Area"槽。
这是我的R会话:
> spatialpolygons
An object of class "SpatialPolygons"
Slot "polygons":
[[1]]
An object of class "Polygons"
Slot "Polygons":
[[1]]
An object of class "Polygon"
Slot "labpt":
[1] 20.50516 57.72918
Slot "area":
[1] 36.85484
Slot "hole":
[1] FALSE
Slot "ringDir":
[1] 1
Slot "coords":
[,1] [,2]
[1,] 16.48438 59.73633
[2,] 22.59277 61.14258
[3,] 24.74609 55.03418
[4,] 17.49512 55.12207
[5,] 16.48438 59.73633
Slot "plotOrder":
[1] 1
Slot "labpt":
[1] 20.50516 57.72918
Slot "ID":
[1] "myMultiPolygons"
Slot "area":
[1] 36.85484
Slot "plotOrder":
[1] 1
Slot "bbox":
min max
x 16.48438 24.74609
y 55.03418 61.14258
Slot "proj4string":
CRS arguments:
+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
> spatialpolygons@bbox
min max
x 16.48438 24.74609
y 55.03418 61.14258
> spatialpolygons@area
Error: no slot of name "area" for this object of class "SpatialPolygons"
> slotNames(spatialpolygons)
[1] "polygons" "plotOrder" "bbox" "proj4string"
> names(spatialpolygons)
[1] "myMultiPolygons"
推荐答案
首先,您应该知道@area
槽不是有关SpatialPolygons*
对象实际面积的可靠信息来源。如?"Polygons-class"
中所述,@area
槽仅用作绘图的辅助工具(防止较小的多边形被较大的多边形涂覆),并且不考虑投影或正确说明多边形中的孔。
要获得准确的面积,您应该使用rgeos::gArea()
表示具有投影坐标参考系的层,或使用geosphere::areaPolygon()
表示位于经度坐标参考系中的层(即CRS(+proj=longlat)
)。
排除这些警告后,如果您确实需要@area
插槽的内容,下面将展示如何获取它们。
主要复杂之处在于,区域窗属于Polygon对象,而不是SpatialPolygons对象(其中Polygon对象是其中的一个元素)。因此,您需要首先深入SpatialPolygons对象以提取到单个Polygon对象。
完成此操作后,只需使用@
运算符提取区域槽的内容。
下面的示例使用在sp
package vignette (warning, pdf)的第7节中创建的SpatialPolygons对象:
require(sp)
# Example pasted in from Section 7 of the sp vignette
Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))
Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))
Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5)))
Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)
Srs1 = Polygons(list(Sr1), "s1")
Srs2 = Polygons(list(Sr2), "s2")
Srs3 = Polygons(list(Sr3, Sr4), "s3/4")
SpP = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3)
# To extract the area of the first (or in your case only) Polygon
SpP@polygons[[1]]@area
# [1] 5.5
# Extract the areas of all three component Polygons
sapply(SpP@polygons, function(x) x@area)
# [1] 5.5 1.5 10.0
## For areas, rgeos::gArea() or geosphere::areaPolygons() are generally more appropriate
## (Note, for instance, that it properly accounts for the hole in the 3rd polygon.)
rgeos::gArea(SpP, byid=TRUE)
# s1 s2 s3/4
# 5.5 1.5 9.0
这篇关于获得S4对象的插槽价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文