Reputation: 13
The following code checks if a coordinate pair belongs to a specific polygon or not. I need to check more coordinate data using loop or something.
Now when it calls the code, it checks every value, but if there is only one coordinate outside the country, the status of all points of the list is 'false'.
library(raster)
library(sp)
library(rgeos)
germany<- getData("GADM",country="Germany",level=0)
df1 <- data.frame(geolok)
ifgermany <-df1 %>%
rowwise() %>%
mutate(germany_area = gContains(germany,SpatialPoints(df1[,9:10],proj4string=CRS(proj4string(germany)))))
Upvotes: 0
Views: 1254
Reputation: 47081
You need to use byid=TRUE
but there should not be a need to loop over points nor polygons
library(raster)
library(rgeos)
germany <- getData("GADM",country="Germany",level=1)
# example points
r <- raster(extent(germany)+10)
values(r) <- 1:ncell(r)
set.seed(10)
xy <- sampleRandom(r, 50, sp=TRUE)
crs(xy) <- crs(germany)
a <- gContains(germany, xy, byid=TRUE)
#or
b <- gIntersects(germany, xy, byid=TRUE)
Upvotes: 0
Reputation: 23574
I do not have your sample data. Hence, what I provide here will help you in some ways. If you need help for your exact situation, please provide sample data from next time. This helps SO users to give you a hand.
I chose Oregon state as a sample sf object. The polygon data is from albersusa package. Then, I created random points. If you draw the ggplot graphic you see where the points are. st_intersects()
check which polygon each data point belongs to and returns a matrix. Each column represents a county in this case, and each row represents a data point. Hence you see 36 columns and 20 rows.
library(sf)
library(albersusa)
mystate <- counties_sf() %>%
filter(state == "Oregon")
# This is a random data set
set.seed(111)
mysample <- st_sample(x = mystate, size = 20)
ggplot() +
geom_sf(data = mystate) +
geom_sf(data = mysample)
# Now I want to find data points in Washington states
check <- st_intersects(x = mysample,
y = mystate,
sparse = FALSE)
colnames(check) <- mystate$name
I leave a part of the matrix here.
Deschutes Jefferson Lake Polk Wheeler Benton Clackamas Coos Crook Gilliam Hood River Jackson Josephine
[1,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[2,] FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[3,] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[4,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE
[5,] FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[6,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE
Upvotes: 0