Here is the situation:
Brief description: I have buffers that overlap; I want to count the number of stores within a certain number of meters from a school.
I specifically want to know how many stores are within 1000 meters from a school, and how many stores are within 2000 meters from a school, as I want to compare the difference. Of course, some of these school buffers overlap. So while a store may be 1500 m from school A, it is only 750 m from school B. Therefore, it counts as being within 1000 m from a school, and should only be counted as being in the 1000m for school B, and not counted for school A. Where a store is within 2000 m of two schools (but not within 1000 m) it needs to count toward the school it is closest to.
So ideally I want the dataset to look like:
School | Stores1000m | Stores2000m |
School A | 3 | 6 |
School B | 2 | 7 |
So I used the st_union function in sf to combine the buffers. This worked well for producing a beautiful map, but then when I used lengths and st_intersects to count the stores within the buffers, it only returned a single number for each type of zone (1000 m vs 2000 m)
My code for these portions is below:
my.buff <-st_buffer(school.sf.utm, 1000)
my.buff2 <-st_buffer(school.sf.utm, 2000)
pts_com<-st_union(my.buff)
pts_pol<-st_cast(pts_com, "POLYGON")
pts_com2<-st_union(my.buff2)
pts_pol2<-st_cast(pts_com2, "POLYGON")
(school$pt_count <- lengths(st_intersects(my.buff, store.sf.utm))) #gives per school but ignores overlapping
(school$pt_count <- lengths(st_intersects(pts_com, store.sf.utm)))
(school$pt_count <- lengths(st_intersects(my.buff2, store.sf.utm)))
(school$pt_count <- lengths(st_intersects(pts_com2, store.sf.utm)))
What would be the ideal code to do what I need to do? I am very lost on how to make this work. Thank you.