Reputation: 1
I have a dataframe with thousands of lat long along with other attributes
> head(df)
created_on latitude longitude day Value Order Total.Value
1 55:40.8 13.01504 80.19199 7/9/2022 2 74 19
2 08:27.0 12.97431 80.19029 7/9/2022 19 49 14
3 39:59.5 12.95778 80.19588 7/9/2022 26 205 50
4 20:43.0 13.07842 80.18144 7/8/2022 1 178 7
5 34:06.2 12.92485 80.09914 7/10/2022 7 106 12
6 08:12.1 12.88727 80.23384 7/10/2022 10 167 17
I have a few polygons in WKT format
head(Poly)
WKT name
1 POLYGON ((80.156 13.058, 80.156 13.040, 80.182 13.052, 80.156 13.058)) Polygon-1
2 POLYGON ((80.2015739 13.050, 80.223 13.033, 80.223 13.049, 80.201 13.050)) Polygon-2
3 POLYGON ((80.185 13.021, 80.200 13.009, 80.202 13.020, 80.185 13.021)) Polygon-3
I want to apply Point-in-Polygon to the df and identify the lat longs that lie in any of these polygons. The output should contain the original attributes of the lat longs as well as the name
of the polygon in which they lie.
I have been able to do it for one polygon at a time but it becomes tedious when I have up to 10-20 polygon to run through. I used the rgeos
package to translate the WKT into a dataframe and the sp
package to apply point in polygon). Below is the code already used
Poly <- read.csv("PIP0.csv")
str <- Poly[2,1]
test <- readWKT(str)
#convert wkt to data.frame of coordinates
coords <- as.data.frame(coordinates(test@polygons[[1]]@Polygons[[1]]))
Points <- read.csv("PIP2.csv")
#logical vector to determine whether points in the df-Point are present in Poly
A <- as.logical(point.in.polygon(Points$latitude, Points$longitude, coords$y, coords$x, mode.checked = FALSE ))
Points$flag[A] <- "This point is present in Polygon"
Thanks,
Upvotes: 0
Views: 99