سؤال

My question is how to compute the angle between two rasters in R? Here is a reproductible example and the error I get:

angle <-function(vectora, vectorb){
      theta <- acos( sum(vectora*vectorb) / ( sqrt(sum(vectora * vectora)) * sqrt(sum(vectorb * vectorb)) )) 
}

raster1 <- raster(ncols=150, nrows=150, xmn=0)
raster1[] <-  rnorm(150*150,ncell(1))
raster2 <- raster(ncols=150, nrows=150, xmn=0)
raster2[] <-  rnorm(150*150,ncell(2))

r.angle <- overlay(raster1,raster2, filename='tes.tif',fun=function(x,y){angle(x,y)})

The error message is the following:

Error in (function (x, fun, filename = "", recycle = TRUE, ...)  : 
  cannot use this formula, probably because it is not vectorized

How can I get that vectorized?

هل كانت مفيدة؟

المحلول

As in the comment, changing two things will fix the problem. The vectorization comes in through raster1[] and raster2[], so you need to modify the application of the function.

function(x,y){angle(x[],y[])})

and add a return at the end of the function angle():

return(theta)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top