I'm trying to get the sum of values from a field on a sf object for all points within a given distance to each point, excluding the value of the point.
set.seed(123);m=matrix(runif(30,1,40),ncol=3) loc<-m %>% as.data.frame %>% sf::st_as_sf(coords = c(1,2)) a<-st_is_within_distance(loc,dist=10) > a Sparse geometry binary predicate list of length 10, where the predicate was `is_within_distance' 1: 1, 6, 10 2: 2, 4 3: 3 4: 2, 4 5: 5, 8 6: 1, 6 7: 7, 9 8: 5, 8 9: 7, 9 10: 1, 10 How can we get a data frame with a list of those 10 points with the sum of V3?
point|sum 1 | sum_of_v3_of(6,10) 2 | sum_of_v3_of(4) ... This is fairly easy to do with postgis but have all the other code in R and would like to learn how to do it.
1 Answer
We may do the following:
data.frame(point = 1:length(a), sum = sapply(a, function(p) sum(loc$V3[p])) - loc$V3) # point sum # 1 1 35.37012 # 2 2 39.77652 # 3 3 0.00000 # 4 4 28.01933 # 5 5 24.17154 # 6 6 35.69203 # 7 7 12.27723 # 8 8 26.57253 # 9 9 22.21857 # 10 10 35.69203 It becomes easy once we notice that a is a list (see str(a)) with elements, e.g., 1, 6, 10 in as its first element, a[[1]], and that loc also is a list with an element V3 that can be reached by loc$V3. So, then using sapply we go over the elements of a, look at the corresponding elements of loc$V3 and sum them up. As a result sapply returns a vector and we are left with creating a data frame or a matrix for the results.