Joao Carreiras
Joao Carreiras

Reputation: 65

terra::rasterize points containing multiple attributes

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.

Upvotes: 1

Views: 792

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47631

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.

Upvotes: 1

Related Questions