这里有两种方法。它们在概念上都相当复杂,但实际上代码非常简单。
fhat <- kde(x=unicef, H=H.scv,compute.cont=TRUE)
contour.95 <- with(fhat,contourLines(x=eval.points[[1]],y=eval.points[[2]],
z=estimate,levels=cont["95%"])[[1]])
library(pracma)
with(contour.95,polyarea(x,y))
# [1] -113.677
library(sp)
library(rgeos)
poly <- with(contour.95,data.frame(x,y))
poly <- rbind(poly,poly[1,]) # polygon needs to be closed...
spPoly <- SpatialPolygons(list(Polygons(list(Polygon(poly)),ID=1)))
gArea(spPoly)
# [1] 113.677
说明
首先,kde(...) 函数返回一个kde 对象,它是一个包含 9 个元素的列表。您可以在文档中阅读相关内容,或者您可以在命令行中键入 str(fhat),或者,如果您使用的是 RStudio(强烈推荐),您可以通过在 Environment 选项卡中展开 fhat 对象来查看此内容。
其中一个元素是$eval.points,即评估核密度估计值的点。默认值是在 151 个等间距点进行评估。 $eval.points 本身就是一个列表,在您的情况下是 2 个向量。因此,fhat$eval.points[[1]] 代表“Under-5”沿线的点,fhat$eval.points[[2]] 代表“Ave life exp”沿线的点。
另一个元素是$estimate,它具有核密度的 z 值,在 x 和 y 的每个组合处进行评估。所以$estimate 是一个 151 X 151 矩阵。
如果您用compute.cont=TRUE 调用kde(...),您会在结果中得到一个额外的元素:$cont,它包含$estimate 中对应于从1% 到99% 的每个百分位数的z 值。
因此,您需要提取对应于 95% 轮廓的 x 和 y 值,并使用它来计算面积。你可以这样做:
fhat <- kde(x=unicef, H=H.scv,compute.cont=TRUE)
contour.95 <- with(fhat,contourLines(x=eval.points[[1]],y=eval.points[[2]],
z=estimate,levels=cont["95%"])[[1]])
现在,contour.95 的 x 和 y 值对应于fhat 的 95% 轮廓。有(至少)两种方法可以获取该区域。一个使用pracma 包并计算
直接用。
library(pracma)
with(contour.95,polyarea(x,y))
# [1] -113.677
负值的原因与 x 和 y 的顺序有关:polyarea(...) 将多边形解释为“洞”,因此它的面积为负。
另一种方法是使用rgeos(GIS 包)中的面积计算例程。不幸的是,这需要您首先将您的坐标转换为“SpatialPolygon”对象,这有点像熊。不过,它也很简单。
library(sp)
library(rgeos)
poly <- with(contour.95,data.frame(x,y))
poly <- rbind(poly,poly[1,]) # polygon needs to be closed...
spPoly <- SpatialPolygons(list(Polygons(list(Polygon(poly)),ID=1)))
gArea(spPoly)
# [1] 113.677