是否有 R 函数可以找到两条线的交点?
Is there an R function to find the intersection of two lines?
我正在为 Advent of Code 2019 的第 3 天第 1 部分工作,其中涉及两根电线的扭转。
我的问题分为两部分:
如果我有一个数据框,其中包含电线经过和转弯的坐标(如蛇和梯子),我如何形成一条线?有我可以使用的功能吗?
这是我试过的代码,但坦率地说,我不确定它是否有效
lines(path1$x, path1$y)
其中 path1 是包含这些坐标的数据框
形成两条直线后,如何得到包含两条直线交点的数据框?
我试过 intersect() 函数,但显然不起作用。
由于您身边没有示例数据,因此很难构建适合您的示例的解决方案。但是,一个简单的 sf
示例可以说明您所追求的目标。
您可以使用 st_linestring
创建线对象并使用 st_intersection
检查它们的交点。下面是一个简单的例子:
library(sf)
#> Linking to GEOS 3.6.2, GDAL 2.2.3, PROJ 4.9.
# Line one has a dot located in (1, 2) and a dot located in (3, 4) connected.
f_line <- st_linestring(rbind(c(1, 2), c(3, 4)))
# Line two has a dot located in (3, 1) and a dot located in (2.5, 4) connected.
s_line <- st_linestring(rbind(c(3, 1), c(2.5, 4)))
# You can see their intersection here
plot(f_line, reset = FALSE)
plot(s_line, add = TRUE)
# sf has the function st_intersection which gives you the intersection
# 'coordinates' between the two lines
st_intersection(s_line, f_line)
#> POINT (2.571429 3.571429)
对于您的示例,您需要将坐标转换为 sf
对象并使用 st_intersection
我正在为 Advent of Code 2019 的第 3 天第 1 部分工作,其中涉及两根电线的扭转。
我的问题分为两部分:
如果我有一个数据框,其中包含电线经过和转弯的坐标(如蛇和梯子),我如何形成一条线?有我可以使用的功能吗?
这是我试过的代码,但坦率地说,我不确定它是否有效
lines(path1$x, path1$y)
其中 path1 是包含这些坐标的数据框
形成两条直线后,如何得到包含两条直线交点的数据框?
我试过 intersect() 函数,但显然不起作用。
由于您身边没有示例数据,因此很难构建适合您的示例的解决方案。但是,一个简单的 sf
示例可以说明您所追求的目标。
您可以使用 st_linestring
创建线对象并使用 st_intersection
检查它们的交点。下面是一个简单的例子:
library(sf)
#> Linking to GEOS 3.6.2, GDAL 2.2.3, PROJ 4.9.
# Line one has a dot located in (1, 2) and a dot located in (3, 4) connected.
f_line <- st_linestring(rbind(c(1, 2), c(3, 4)))
# Line two has a dot located in (3, 1) and a dot located in (2.5, 4) connected.
s_line <- st_linestring(rbind(c(3, 1), c(2.5, 4)))
# You can see their intersection here
plot(f_line, reset = FALSE)
plot(s_line, add = TRUE)
# sf has the function st_intersection which gives you the intersection
# 'coordinates' between the two lines
st_intersection(s_line, f_line)
#> POINT (2.571429 3.571429)
对于您的示例,您需要将坐标转换为 sf
对象并使用 st_intersection