0
votes

I am looking to dissolve a spatial lines dataframe by an attribute. In my data set there is a river line where multiple segments run through the same habitat type and I want one continuous line segment through each habitat type.

raster:aggregate works great for spatial polygons and although the documentation mentions spatialpolygons/lines the description and example only mentions spatial polygons.

Whenever I run on a spatial line dataframe I get the error: Error in h(simpleError(msg, call)) : error in evaluating the argument 'obj' in selecting a method for function 'spChFIDs': error in evaluating the argument 'obj' in selecting a method for function 'bbox': assignment of an object of class “character” is not valid for slot ‘proj4string’ in an object of class “Spatial”; is(value, "CRS") is not TRUE In addition: Warning message: In proj4string(x) : CRS object has comment, which is lost in output:

Some share friendly code to highlight the problem:

library(raster)
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
x <- rasterToContour(r)

#create duplicate data that is slightly shifted so there is still some spatial overlap
x2 <- shift(x, dx=100, dy=-100)

#combine the two spatial dataframes
x3 <- raster::bind(x, x2)

#aggreate or "dissolve" the features by "level"
test <- raster::aggregate(x3, by = "level")

#vs how it works on a spatial polygon
p <- shapefile(system.file("external/lux.shp", package="raster"))
test2 <- raster::aggregate(p, by = "NAME_1")

thank you

1

1 Answers

0
votes

That is a bug, here is work-around using terra (the replacement for raster)

library(raster)
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
x <- rasterToContour(r)
x2 <- shift(x, dx=100, dy=-100)
x3 <- raster::bind(x, x2)


a = terra::aggregate(terra::vect(x3), "level")
# coerce back
b = as(a, "Spatial")

# or via sf
b = sf::st_as_sf(a)
d = as(b, "Spatial")