1

I am interested in calculating the proportion of GPS points that fall within protected areas. I can do this with my full data set with the code I show below.

However, I would like to group this data by the id column and get a measure of overlap for A and B separately.

Thanks

# load packages
library(wdpar)
library(dplyr)
library(sf)

# download protected area data 
# (excluding areas represented as point localities)
sa_raw_pa_data <- wdpa_fetch(c("South Africa"))
sa_raw_pa_data 

# reproject data
sa_pa_data <- st_transform(sa_raw_pa_data, 4326)

# plot it
# plot(sa_pa_data)

# create some random data
set.seed(123)
d = data.frame(long=runif(100,16,38), lat=runif(100,-47,-22))
d$id <- c(rep("A", 50), rep("B", 50))

# measure the overlap
pts <- st_as_sf (d, coords = c ("long", "lat"), crs = 4326)
res <- st_intersects (pts, sa_pa_data)

length (unlist (res)) / nrow (pts) # fraction of intersecting points

1 Answer 1

5

You could split your points into a list where each element is a group (A, B). Then you can use lapply to iterate over each group.

point_list <- split(pts, pts$id)  # split points into list by id

res <- lapply(point_list, function(x) 
   length(unlist(st_intersects(x, sa_pa_data))) / nrow(x)
)

unlist(res)
   A    B 
0.06 0.02 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.