To work out why your code isn't returning the expected result, you should probably run chunks of your code from the inside out. For example, does forest_cov[i] > 0 == 1
return what you expect it to return for raster 1? (I suspect not, since according to your comments, forest_cov
is a character vector and so the logical comparison of element i
to 0 is not sensible.) But, if so, does forest_cov[i][forest_cov[i] > 0 == 1]
return what you expect, and so on.
Here's how I would approach the problem.
Prepare some fake data:
# Write out three fake rasters to temp files
writeRaster(stack(replicate(3, raster(matrix(runif(100), nc=10)))),
{f <- tempfile()}, bylayer=TRUE, format='ascii')
# Filenames of these fake rasters
rasters <- paste0(f, '_', 1:3, '.asc')
Calculate the frac.dim.index
(i.e. 11th element of PatchStat
result) of each raster:
sapply(rasters, function(x) {
require(SDMTools)
PatchStat(raster(x) >= 0.1)[11]
})
Alternatively, if all the rasters referred to in your character vector have consistent extent and dimensions, then you can perform the operation on a stack as follows:
s <- stack(rasters) >= 0.1
sapply(seq_len(nlayers(s)), function(i) PatchStat(s[[i]])[11])