0
votes

I need to estimate the weighted average of raster values for the polygon shown in squares. I want to obtain raster value and its weight within each square in the polygon shape. (As shown in this post: How can I extract an area weighted sum from a raster into a polygon in R?)

But, please see my code below and the image of what I am getting as weights. Can somebody correct me what I am doing wrong here and why my output is different from as shown in the above post.? I want to obtain an output like in the post above. Seems likes the weights I am getting is wrong too.

Please see the attached input data set here: https://bft.usu.edu/w8crs

Thanks.

library(raster)
library(sp)
library(rgdal)
library(rgeos)

rlist = list.files(getwd(), pattern = "tif$", full.names = TRUE)
inshp = "Test" 
rdata <- rlist[1]

r <- raster(rdata)
sdata <- readOGR(dsn=getwd(), layer=inshp)
sdata <- spTransform(sdata, crs(r))

extract(r, sdata, weights=TRUE)

enter image description here

Output:

enter image description here

[[1]]
    value weight
 56.75139      1

[[2]]
    value weight
 61.18781      1

[[3]]
    value weight
 56.75139      1

[[4]]
    value weight
 61.18781      1
1

1 Answers

0
votes

Here is a reproducible example

library(raster)
packageVersion("raster")
#[1] ‘2.8.4’
r <- raster(xmn=0, xmx=1, ymn=0, ymx=1, nrow=2, ncol=2)
values(r) <- 1:4

m <- matrix(c(0.4, 0.6, 0.8, 0.6, 0.7, 0.2, 0.3, 0.2), ncol=2, byrow=TRUE)
s <- spPolygons(m)
plot(r); lines(s)

extract(r, s, weights=TRUE)
#[[1]]
#     value weight
#[1,]     1 0.0625
#[2,]     2 0.1875
#[3,]     3 0.3125
#[4,]     4 0.4375

This did not work for you, because your polygon was very small relative to the raster cell size. I have changed the function, such that it increases the precision for those cases. I now get this with your data:

> extract(r, sdata, weights=TRUE)
[[1]]
    value weight
 56.75139      1

[[2]]
        value    weight
[1,] 61.18781 0.6592593
[2,] 56.75139 0.3407407

[[3]]
    value weight
 56.75139      1

[[4]]
        value    weight
[1,] 61.18781 0.5522388
[2,] 56.75139 0.4477612

To make it reproducible without downloads, for one of your polygons:

library(raster)
r <- raster(ncol=2, nrow=1, xmn=596959.624056728, xmx=624633.120455544, ymn=568805.230192675, ymx=582641.978392083, crs='+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=37.5 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m')
values(r) <- c(61.18781, 56.75139)    
g <- data.frame(matrix(c(rep(1, 18), rep(0,6), 611318.079488842,611440.751254539,610712.115334383,609842.749239201, 609703.303842618,611318.079488842,581038.816616668,579434.971927127, 579381.167042005,579315.223934334,580917.724282178,581038.816616668), ncol=6))
colnames(g) <- c('object','part','cump','hole','x','y')
p <- as(g, "SpatialPolygons")
crs(p) <- crs(r)

extract(r, p, weights=TRUE)

#[[1]]
#        value    weight
#[1,] 61.18781 0.6592593
#[2,] 56.75139 0.3407407