# Count number of points on a line in R

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`?

• "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. Nov 25, 2018 at 20:08

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:

``````library(rgdal)
library(data.table)

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

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)
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.