Search code examples
rextractterra

Can different functions be used to extract different types of layers of a raster using terra::extract?


My goal is to extract data from a raster for a set of polygon locations. The raster has many numeric variables and some categorical. I would like to extract the values conditional on this, e.i., if the variable is numeric get the mean for each polygon and if the variable is categorical get the mode.

Now I'm doing this (see that the 'numeric' layer is numeric, and the 'categorical' has numbers that represent categories):

extract_numeric <- terra::extract(x = raster,
                                  y = vect(polygons),
                                  fun = mean,
                                  layer = 'numeric',
                                  rm.na=T)

extract_categorical <- terra::extract(x = raster,
                                      y = vect(polygons),
                                      fun = mode,
                                      layer = 'categorical',
                                      rm.na=T)

extract <- c(extract_numeric, extract_categorical)

Is it possible to extract the values all in one depending on the layer type? Even if I would like that different numeric layers get different fun for the extraction. Can it be done?

Thanks!


Solution

  • No, that cannot be done. What you can also do is subset x using names or indices

    e_num <- extract(x[[c(1:3, 6:8)]], v, fun=mean)
    e_cat <- extract(x[[4:5]], v, fun=mean)
    

    But that is similar to using the layer argument.

    You can also do

    e_list <- extract(x, v)
    

    And then lapply your own function on that list.