I have a SpatialLinesDataFrame and a SpatialPointsDataFrame. I want to calculate the number of points that fall on a line by a specific field in the lines data frame.

Example: I have a river network broken up into 125 fragments with a specific length: I want to count the number of points that fall in each of the 125 fragments. Is there a function to do this like poly.counts? enter image description here

  • 5
    "point on a line" is tricky, due to arithmetic rounding. Better to compute the distance from point to nearest line point and use a threshold.
    – Spacedman
    Nov 25, 2018 at 20:08

1 Answer 1


You can use the function over() to emulate the poly.counts you mentioned. There will still be the issue with the rounding of coordinates @Spacedman mentioned, but looking the image you attached it looks like points could match. Having your data (or your code) could help us to provide more precise assistance; I provide you with some main lines to follow to apply the over() function:


rivers <- readOGR(...) # load your rivers' data
rivers@data$id <- 1:nrow(rivers) # to make sure there is data associated with your rivers' dataset
rivers@data <- data.table(rivers@data)

points <- readOGR(...) # load your SpatialPointsDataFrame

Assuming each of the 125 fragments you mention is a different object of your SpatialLinesDataFrame, you can loop over as

rivers@data$count <- as.numeric(NA)
for (i in 1:nrow(rivers)) {
    rivers[i,'count'] <- sum(!is.na(over(points, rivers[,'id'])))

The over() function retrieves a vector with the dimension of points containing the 'id' of the rivers[i,'id'] feature (each fragment) laying under each point of points. The points which do not lay over a line would have a <NA> associated to it. Thus, sum(!is.na(...)) provides you with the number of points which have been found to be laying over the fragment. Looping over each fragment, you would have the count for each of them.

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.