I have a shapefile with points for 6 individuals and another shapefile with 6 polygons (one per individual). Every individual has the same id in both files.
I want to intersect both layers in order to obtain, for each individual, the points within the corresponding polygon.
I've tried with only one individual, using the function raster::intersect()
and it works perfectly. However, I will have to repeat this process for other animals so I would like to have a loop that could do this automatically (but I am not very familiar with loops).
I've tried several options, and so far this was the only one that worked partially:
for (i in unique(SLO_repr$id)) {
for (j in unique(HR95_all$id)) {
if ((!is.na(SLO_repr$id[i])) == (!is.na(HR95_all$id[j]))) {
a <- raster::intersect(SLO_repr, HR95_all)
writeOGR(a, dsn= getwd(), paste0("points_withinHR", "_", i), driver = "ESRI Shapefile",overwrite_layer=TRUE)}
}
}
The problem with this one is that, in each shapefile, all points within each polygon are included. So, the raster::intersect()
function worked, but it seems I didn't select the i
and j
properly...?
To build this loop, I followed this question: Loop to check multiple polygons overlap in r
I was also wondering if I really need to have a nested loop? Because all id's are the same, so in the condition, when it gets on i
for SLO_repr$id
, it should select the same value for HR95_all$id
?
So I've tried this loop:
for (i in unique(SLO_repr$id)) {
if ((!is.na(SLO_repr$id[i])) == (!is.na(HR95_all$id[i]))) {
a <- raster::intersect(SLO_repr[[i]], HR95_all)
writeOGR(a, dsn= getwd(), paste0("points_withinHR", "_", i), driver = "ESRI Shapefile",overwrite_layer=TRUE)}
}
But I get this error: "Error in as.vector(y) : no method for coercing this S4 class to a vector
"
Any ideas about this?