[英]R implementation to union of overlapping rectangles
I am trying to solve a problem where I have multiple overlapping rectangles and I need to find the combined area of the rectangles. 我试图解决一个问题,我有多个重叠的矩形,我需要找到矩形的组合区域。 Intersecting portion of the rectangles need to looked at just once.
矩形的相交部分只需要查看一次。 I searched online and I found that Line sweep algorithm will work perfectly for me, as explained here : What is an Efficient algorithm to find Area of Overlapping Rectangles
我在线搜索,我发现线扫描算法对我来说非常有效,如下所述: 什么是找到重叠矩形区域的高效算法
My question is, Does R have something similar already implemented? 我的问题是,R是否已经实现了类似的东西? I could not find anything similar in R. I do not want to reinvent the wheel if it already exists.
我在R中找不到类似的东西。如果它已经存在,我不想重新发明轮子。
Interesting question. 有趣的问题。 Suppose we've four rectangle coordinates as shown below:
假设我们有四个矩形坐标,如下所示:
require(data.table) # v1.9.7+
dt = data.table(x0 = c(7,17,5,1), x1 = c(14,27,11,10),
y0 = c(1,55,6,14), y1 = c(10,70,20,34))
dt[, id := .I] # add row numbers
# x0 x1 y0 y1 id
# 1: 7 14 1 10 1
# 2: 17 27 55 70 2
# 3: 5 11 6 20 3
# 4: 1 10 14 34 4
To see if rectangle i
intersects with j
, the condition, IIUC is: 要查看矩形
i
是否与j
相交,条件IIUC为:
x0_i <= x1_j, x1_i >= x0_j, y0_i <= y1_j, y1_i >= y0_j, where
x0_i < x1_i, x0_j < x1_j, y0_i < y1_i, y0_j < y1_j
This can be achieved with a conditional join, which was recently implemented in the current development version of data.table, v1.9.7. 这可以通过条件连接来实现,该连接最近在data.table,v1.9.7的当前开发版本中实现。 See installation instructions here .
请在此处查看安装说明
ans = dt[dt,
.(id1 = pmin(i.id, x.id), id2 = pmax(i.id, x.id),
x0 = pmax(x.x0, i.x0), x1 = pmin(x.x1, i.x1),
y0 = pmax(x.y0, i.y0), y1 = pmin(x.y1, i.y1)),
on = .(x0 <= x1, x1 >= x0, y0 <= y1, y1 >= y0)
][id1 != id2]
ans = unique(ans)
# id1 id2 x0 x1 y0 y1
# 1: 1 3 7 11 6 10
# 2: 3 4 5 10 14 20
Basically this performs a self-join . 基本上这会执行自联接 。 For each row in
dt
, it finds all matching indices with itself based on the condition provided to the on=
argument, and based on the matching rows it extracts indices of the two rectangles and their intersecting portions. 对于
dt
每一行,它根据提供给on=
参数的条件找到所有匹配的索引,并根据匹配的行提取两个矩形及其相交部分的索引。 The id1 != id2
filters out self-overlaps.. id1 != id2
过滤掉自重叠..
Then we make sure that are no duplicates. 然后我们确保没有重复。 The result shows which rectangle
id1
overlaps with which ones id2
, and their intersecting region x0, x1, y0, y1
. 结果显示哪个矩形
id1
与哪个id2
重叠,以及它们的交叉区域x0, x1, y0, y1
。
Is this more or less what you were looking for? 这或多或少是你想要的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.