1

As in the question I have several points, lets call them A, B, and C (but they can be more) of which I know the position in (x, y). I also have a defined area ranging in between [1-n] on both axis. I need to find all the points that fall in the polygon that is generated by A, B, and C.

Since I don't have a set of points, I thought to use the whole range for both x and y axes, i.e. [1-n], as the set of possible points falling in the polygon generated by A, B, and C but I am not sure whether this could be what the function was designed for.

At this stage, I tried something involving the following function (of which I found other questions here in SO).

#define the range as the possible points falling in the polygon
allPointsX <- allPointsY <- c(1:2048)
#get some coordinates for three points generating the actual polygon (which in this case is a simple triangle)
xCoord <- c(127, 120, 152)
yCoord <- c(77, 96, 107)
#look for points into the polygon
points <- point.in.polygon(allPointsX, allPointsY, xCoord, yCoord)

but either I am not getting the output (which is all zeros: all(points==0)), or this is not what I am looking for.

Any suggestions? What am I missing?

gabt
  • 668
  • 1
  • 6
  • 20
  • 2
    The range of "all possible points" would be different from what you've created. You created a line, but I think you wanted a grid? `allpoints <- expand_grid(1:2048, 1:2048)`. Note that this is a large data frame. Then you'd call `points <- point.in.polygon(allpoints[,1], allpoints[,2], xCoord, yCoord)` – BrianLang Oct 12 '20 at 11:04
  • @BrianLang I believe you're right! I've tried it out and...just to make your code executable...```expand_grid``` should be ```expand.grid``` with the dot and not the underscore! anyway...thank you! – gabt Oct 12 '20 at 12:07
  • 1
    That's right. `expand_grid` is from the package `dplyr`! whoops :-) – BrianLang Oct 12 '20 at 12:38

1 Answers1

2

Your code is correct. It is just that all of your points lie outside the triangle.

library(tidyverse)

ggplot(mapping = aes(x, y)) +
  geom_point(data = tibble(x = allPointsX, y = allPointsY)) +
  geom_polygon(data = tibble(x = xCoord, y = yCoord)) +
  xlim(75, 160) +
  ylim(75, 160)

plot

Here is a point that lies inside the triange.

sp::point.in.polygon(127, 78, xCoord, yCoord)
#> [1] 1
Paul
  • 8,734
  • 1
  • 26
  • 36
  • I believe that the real issue is the one @BrianLang pointed out in the comment! I'll try it out with this nice ggplot you provided and see what happens. – gabt Oct 12 '20 at 12:09
  • yep it actually worked with the exception that my grid was a line as your plot clearly states. – gabt Oct 12 '20 at 12:20