Error with M values and st_zm function in sf package

75 views Asked by At

I have imported a multipolygon shp file containing different forest patches (called 'patch'): patch

Then, I have bricked different Sentinel-2 bands for the same region in a raster called 'SenBel' data: SentinelB6-8_patch
code to brick:

    SenBel <- brick(Sentinel_noCl_B6_10m,
                Sentinel_noCl_B7_10m, Sentinel_noCl_B8, nl=3)

I would like to calculate the mean reflectance value for each band per patch and add this in the attribute table of the shp file as a new column with the name of the band respectively. First I created this function:

`f1 <- function(raster, column_name) {
    values <- extract(raster, patch)
    mean_values <- unlist(lapply(values, mean, na.rm = TRUE))
    patch[[column_name]] <- mean_values
    }

#Calculate mean values for bands
bands <- c( "B6", "B7", "B8")
for (i in bands) {
  f1(SenBel[[i]], paste0("mean", i))
}`

I got following error: Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 'addAttrToGeom': geometries containing M not supported by sp use st_zm(..., what = "M") When I tried to use the st_zm function as follows:

 `st_zm(patch,drop=TRUE, what="ZM")
 `

I kept getting the same error in the function above, as if nothing changed. If I check for M values, it still states 'TRUE':

`contains_M_values <- function(x) {
    coords <- st_coordinates(st_geometry(x))
    dim(coords)[[2]] > 2  # Check if coordinates have more than 2 dimensions (indicating M values)
 }
contains_M_values(patch)
[1] TRUE`

Is there another way to solve this problem? I don't fully understand either what M values are or how my shp file contains them. Thanks in advance!

1

There are 1 answers

3
Edzer Pebesma On BEST ANSWER

Your contains_M_values does not check whether the m values are gone; use st_zm the way you did and then print the object; it should now say Dimension: XY indicating M has been removed. Read ?st_coordinates to find out what that function returns (in addition to vertices, the ring IDs).