R – Count Multilinestring Elements Crossing a Raster Cell

countrrasterrasterization

I have a shapefile with several MULTILINESTRING geometries, representing the borders of some species' distributions, and I want to count the number the number of species occurring in each cell.

I used the rasterize function from the terra package:

count.sp <- terra::rasterize(sp.lines, rast.w, fun = "count")

As an example, the lines in the figure below represent the borders of the distribution of a given species "X":

Example with a species whose distribution is subdivided into several elements

In the example, species' distribution was subdivided into several disjoint parts crossing the same raster pixel. With the code above, I got as a result the number of parts in each pixel (8 and 5, respectively), whereas I would like to get all the parts belonging to the same species and crossing the same pixel be counted as a single occurrence (i.e., I would like to get 1 in both pixels in the example below).

I also tried the function "sum" (with no field, and I obtained 208 and 130, I don't understand what these values represent)

You can find some example data here (1 shapefile with just 2 species and the raster)

What I am missing?

Best Answer

Following @JeffreyEvans suggestion, I achieved it using an "extract" approach:

First, I assigned an unique ID to each raster pixel:

values(rast.w) <- 1:ncell(rast.w)

Then, I used the extract function from the package terra to get the ID of the cells crossed by each species:

sp <- terra::extract(rast.w, sp.lines)

Then, I converted the resulting list into a dataframe with the ID of each cell (first column) and the number of species occurring in each of them (second column, aggregated counting)

count <- as.data.frame(table(unlist(sp)))

Finally, I created a new raster from the first one, replacing ID values with the counting result:

newraster <- rast.w
newraster <- subs(rast.w, count, by = "test")
Related Question