1

I have a SpatVector with 10 points and 2 attributes (i_1, i_2). I need to summarise my SpatVector over one grid cell covering those 10 points and thought terra::rasterize was the most appropriate function to do just that. The output of rasterize needs to take into account both attributes of the SpatVector. However, I just can't figure it out how to pass the attributes to the function. E.g., using this odd function :

fn <- function(i_1, i_2,...) {
   out <- mean(i_1*i_2, na.rm = T)
   return(out)
}

terra::rasterize(points, raster, fun = fn(i_1, i_2))

returns a raster with 1 line and 1 column (what I wanted) but with value 1, whereas if I do:

fn(points$i_1, points$i_2)

I get what I'm supposed to be getting.

Either I'm missing how to pass the attributes of the SpatVector to the function in terra::rasterize or this function can't handle this analysis.

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

1 Answers1

1

It would seem to me that you can combine the two fields prior to using rasterize

 points$i_12 <- points$i_1 * points$i_2
 out <- rasterize(points, raster, "i_12", fun = mean, na.rm=TRUE)

The same principle applies for more complex functions. First apply the function, then rasterize. Unless the function is complex in the sense that it, for example, takes the mean of each variable and adds these. In that case, you need to rasterize in steps.

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • Thank you Robert! That does help, but the point is that I'm failing to pass the attributes of the SpatVector to the function in rasterize. I used a very simple example, but what I'm trying to do is much more complex. I do have a more complex function using at least 4 attributes from a SpatVector to compute one output value that I want to write to the raster. I just don't know if I'm not writing a proper function or if this is a limitation of rasterize. Like I said, the function works alright if applied to a dataframe. – Joao Carreiras Feb 28 '22 at 22:43
  • rasterize works with a single variable. That can be a limitation, but it is easy to work around, I think. At least I have not seen an example where this is not the case. – Robert Hijmans Mar 01 '22 at 08:56
  • Thank you Robert for clarifying that. I'll have a look at alternative ways to combine the attributes and then rasterize. – Joao Carreiras Mar 01 '22 at 10:17