0

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!

  • 2
    Maybe you could use a custom `fun` that chooses mean or mode depending on the layer type. BTW, providing a minimal reproducible example really helps people to test potential solutions. Almost all questions, with only few exceptions, should include an MRE. What is missing here is some example data for the raster object. – dww Jan 28 '22 at 14:33
  • 1
    ... but honestly, I wonder how much it is even a good idea to mix up the types like this. Probably it is cleaner to just keep them separate. Otherwise, how can we be sure that the results can all be coerced to a single type in the final vector without losing information. – dww Jan 28 '22 at 14:40

1 Answers1

0

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.

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63