문제

I have aerial images of forests where I need to compute fragmentation index. I know how to do it for any individual image, but I want to use loop because the is a bunch of them.

# required libraries
library(raster)
library(SDMTools)

The desired index value is element number 11. But before I extract this value I need to replace all values to "1" (from original range 1-100)

# Individual raster can be done like this:
x <- raster(forest_cov[1])
x[x > 0] = 1
PatchStat(x)[11]


# I have tried this loop but it is not working
rast<-numeric(41)
for (i in 1:41) {
rast[i] <- PatchStat(raster(forest_cov[i][forest_cov[i] > 0 == 1]))[11]
                }

The problem is that I do not know how to replace all values in raster to 1 (inside code). What am I doing wrong?

도움이 되었습니까?

해결책

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])
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top