0

I am working on Day 3 part1 of Advent of Code 2019, which involves two wires twisting and turning.

There are two parts to my question:

  1. If I have a data frame with the coordinates where the wire passes and takes a turn (like snake and ladders), how do I form a line? Is there a function I could use?

    This is the code I've tried, but to be frank I'm not sure whether it works or not

    lines(path1$x, path1$y)
    

    where path1 is the data frame containing those coordinates

  2. After I have formed the two lines, how can I get a data frame containing the points of intersection of those lines?

    I have tried the intersect() function which clearly does not work.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Yi Ting
  • 13
  • 5
  • Can you please post the path coordinates? I can't log onto advent of code – pgcudahy Dec 05 '19 at 07:09
  • Also: https://stackoverflow.com/questions/34248347/r-locate-intersection-of-two-curves, https://stackoverflow.com/questions/20519431/finding-point-of-intersection-in-r. – AkselA Dec 05 '19 at 07:10
  • `ploy(path1,ty="l")` – Onyambu Dec 05 '19 at 07:11
  • @pgcudahy Here are the first 10 positions that wire1 passes through. I can't post them all due to character limit. (0, 0), (1003,0) (1003, -138), (662, -138), (662, 660), (-260, 660), (-260, 813), (461, 813), (461, 636), (164, 636) – Yi Ting Dec 05 '19 at 07:16

1 Answers1

1

Since there is not example data from your side it's difficult to build a solution that fits your example. However, a simple sf example can exemplify what you're after.

You can create line objects with st_linestring and check their intersection with st_intersection. Below is a simple example:

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)

For your example, you would need to transform your coordinates into an sf object and use st_intersection

cimentadaj
  • 1,414
  • 10
  • 23