I have a raster with pixel values from 0 to 20, and I'm trying to count each pixel value with R package exactextractr. I have the raster ('def'), a SpatialPolygons object ('grid10') and an empty dataframe ('results'), pre-filled with NAs, with 21 columns x 10066 rows (there are 10066 polygons for which I want to extract counts). This is what I get:
> for (i in 0:20){
+ z <- exact_extract(def, grid10, function(value, count) {
+ count[value == i]
+ })
+ results[,i+1] <- z
+ }
|==================================================================================================================| 100%
Error in `[<-.data.frame`(`*tmp*`, , i + 1, value = list(c(NA_real_, NA_real_, :
replacement element 2 has 754 rows, need 10066
In addition: Warning message:
In `[<-.data.frame`(`*tmp*`, , i + 1, value = list(c(NA_real_, NA_real_, :
replacement element 1 has 10284 rows to replace 10066 rows
Can anyone suggest a correction?...I can't be far away from the correct code, as the following code works to extract the proportion coverage for each pixel value:
for (i in 0:20){
message(i)
z <- exact_extract(def, grid10, function(value, coverage_fraction) {
sum(coverage_fraction[value == i],na.rm = T) / sum(coverage_fraction,na.rm = T)
})
results[,i+1] <- z
}
The code to set up the 'results' df was:
lenval <- length(grid10@data$left)
results <- data.frame(matrix(data=NA, nrow = length(seq(1:lenval)),
ncol = length(seq(1:21))))