Hello esteemed R experts,

I am attempting the use the 'focal' function in the raster package to calculate the mean of an annulus (as opposed to a focal mean of a circle or square).

>From what I can tell, this requires me to generate a weights matrix and use this matrix in the focal function.

The problem, however, is that there are edge effects because the weights to not get readjusted along the boundary/edge of my raster. Therefore, the focal mean of the annulus near the boundary of my rasters are lower than would be expected.

Code is below that repeats the problem. Please help if you can.

Thank you,
Sean Parks


##################################################################
##################################################################

library(raster)
the.raster <- raster(matrix(round(rep(seq(1,5, 0.0001), 250)), nrow=250, ncol=250))

#############################################################
# Create annulus weights matrix
# There is actually an error in the weights matrix that I will figure out later
# Bonus points if you can identify and fix it
# This error does not affect the overall issue that I am attempting to address
# Please don't [publicly] make fun of me for this clunky code
#############################################################
w <- focalWeight(the.raster, d=0.025, type='circle')
w.rev <- w
for (i in 1:ncol(w)) {
               col <- w[,i]
               num.recs <- length(which(w != 0))

               first.rec <- match(1/num.recs, col)
               last.rec <- length(col) - (first.rec- 1)
               non.recs <- seq(1:length(col))
               non.recs <- non.recs[-c(first.rec, last.rec)]

               col[non.recs] <- 0
               w.rev[,i] <- col
}

count <- length(which(w.rev != 0))
w.rev[w.rev != 0] <- 1/count

###############################################################
# End of creating weights matrix
###############################################################

# Now make and view the annulus raster
# Note the edge effects in the top and bottom of the plot

annulus.raster <- round(focal(the.raster, w=w.rev, na.rm=T, pad=T))
plot(annulus.raster)

# END

#################################################################
#################################################################






This electronic message contains information generated by the USDA solely for the intended recipients. Any unauthorized interception of this message or the use or disclosure of the information it contains may violate the law and subject the violator to civil or criminal penalties. If you believe you have received this message in error, please notify the sender and delete the email immediately.

	[[alternative HTML version deleted]]

