首页 > 解决方案 > R中几何形状的计算

问题描述

我想在 R 中显示相交的几何形状并进行一些计算(例如面积、大小)。有人能告诉我该怎么做吗?(之前的措辞“有人可以为此推荐一个合适的包”导致问题被关闭,但这确实是我所需要的,我熟悉解析几何)。

互联网上的广泛研究产生了大量关于地理物体和球面几何的材料。在这里,我只对笛卡尔坐标中的普通二维形状感兴趣。

一个简单的例子会很好:一个圆和一个矩形(大小和位置不重要)相交,并且估计相交区域的最小周围圆的面积和半径。

我可以使用图像分析库来完成这项工作并立即做好准备,但 R 确实是以下评估的首选工具。

标签: rgeometry

解决方案


你可能想使用sf包。虽然这个包最常用于地理空间数据,但它也可以处理几何交叉点。让我提供一个计算矩形和类椭圆形状重叠的基本示例。我还将plotrix简要地使用包来生成类似椭圆形的数据,因为您没有在问题中放入示例数据。

library(sf)
plot(0)
#make a oval, then put oval points in a dataframe
oval<-plotrix::draw.circle( 0, 0, .5 ) %>% data.frame(.)

#combine oval data points into an sf object. Convert points to polygon
oval_sf <- sf::st_as_sf(oval, coords = c("x", "y")) %>% 
  sf::st_combine(.) %>% 
  sf::st_cast(., "POLYGON")

#Make a rectangle. I make a 1 X 1.5 rectangle in the example.
rectangle <-sf::st_polygon(list(cbind(c(0, 0, 1.5, 1.5, 0), c(0, 1, 1, 0, 0))))

#Sum of area of the two separate shapes
total_area <- st_area(rectangle) + st_area(oval_sf)
#Sum of area of two shapes if combined into one shape
combined_area<-st_area(st_union(oval_sf,rectangle))
#Then calculate the area of the intersection
intersection_area <- total_area - combined_area
intersection_area
[1] 0.4716912

有关说明中更复杂交叉点的示例sf,请查看: https ://r-spatial.github.io/sf/reference/geos_binary_ops.html


推荐阅读