0

I have a municipality polygon that looks like this:

shp_muni
class       : SpatVector 
geometry    : polygons 
dimensions  : 1, 1  (geometries, attributes)
extent      : 5.08748, 5.467728, 52.43524, 52.69111  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 
names       :   PC4
type        : <int>
values      :  8244

I have a raster that covers the entire world with resolution of 0.25

class       : SpatRaster 
dimensions  : 696, 1440, 1  (nrow, ncol, nlyr)
resolution  : 0.25, 0.25  (x, y)
extent      : -180, 180, -90, 84  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 
source      : memory 
name        : year_value 
min value   :        1 
max value   :      100 
    

I want to calculate mean, max, and min of raster cells that fall within the municipality including the cells that intersect with the boundary of the polygon. I did this:

cells_score <- terra::extract(temp_rast, shp_muni, exact = T, cells = T, na.rm = TRUE, as.raster = F)
cells_score
    
ID year_value   cell   fraction
 1       14      180741 0.24591428
 1       14      180742 0.50551934
 1       17      182181 0.03271280
 1       16      182182 0.09146393
   

Using the above, I can calculate min(=14), max(=17) and mean (using the fraction as weights after re-normalising the fraction so that it adds up to 1). However, if I do the following, I get a different number for min:

terra::extract(temp_rast, shp_muni, "max", touches = T, na.rm = TRUE, as.raster = F)
ID year_value
1       17
    
terra::extract(temp_rast, shp_muni, "min", touches = T, na.rm = TRUE, as.raster = F)
ID year_value
1        0
    

Why I am getting different values using the two approaches?

1 Answer 1

0

I cannot reproduce that with these example data

library(terra)
v <- vect(system.file("ex/lux.shp", package="terra"))[1,]
r <- aggregate(rast(system.file("ex/elev.tif", package="terra")), 10, mean, na.rm=TRUE)

extract(r, v, touches=T, na.rm=TRUE)[,2] |> sort()
# [1] 352.8333 404.6000 415.4900 448.0000 457.7356 460.4800 464.3478 465.9756 469.1800
#[10] 476.0698 478.1951 494.5867
 
extract(r, v, fun=min, touches=T, na.rm=TRUE)
#  ID elevation
#1  1  352.8333
extract(r, v, fun=max, touches=T, na.rm=TRUE)
#  ID elevation
#1  1  494.5867

I do note that you use different options when you are using argument "fun" (touches=TRUE instead of exact=TRUE); that might explain it. Also, extract does not have an argument as.raster. And I am not sure why the title of your question refers to summary as you are not using it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.