I want to do some calculations with a list of rasters of lakes. Therefore I wrote a loop, which has so far worked fine when I only used rasters. Now I have calculations with rasters and numeric vavlues and somehow this causes an error in the overlay function. My code is:
list files
NDVI <- list.files(path =
"C:/Users/Felix/Desktop/Bachelorarbeit/Daten/Datenverarbeitung_R/L8_NDVI",
pattern = 'NDVI.tif$', full.names=T)
define function
fun_PV <- function(x,y,z){((x-y)/(z+y))^2}
Loop
for(i in seq_along(NDVI))
{
PV <- overlay(x = raster(NDVI[i]),
y = minValue(raster(NDVI[i])[[i]]),
z = maxValue(raster(NDVI[i])[[i]]),
fun = fun_PV)
sat = substr(NDVI[i], 73, 77)
path = substr(NDVI[i], 78, 84)
date = substr(NDVI[i], 85, 92)
setwd
("C:/Users/Felix/Desktop/Bachelorarbeit/Daten/Datenverarbeitung_R/L8_PV")
writeRaster(PV,filename = paste0(sat, path, date, '_PV', '.tif'))
removeTmpFiles(h=0.1)
}
The error I get is:
Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘overlay’ for signature ‘"RasterLayer", "numeric"’
1 Answer 1
The overlay
function is unnecessary since you are only using one raster layer, you can pass the the raster and two values directly to your function. Also, I'm not clear why you are using the [[i]]
subset within the overlay
function. These are single-band rasters, correct?
for(i in seq_along(NDVI))
{
r <- raster(NDVI[i])
PV <- fun_PV(r, minValue(r), maxValue(r))
sat = substr(NDVI[i], 73, 77)
path = substr(NDVI[i], 78, 84)
date = substr(NDVI[i], 85, 92)
setwd("C:/Users/Felix/Desktop/Bachelorarbeit/Daten/Datenverarbeitung_R/L8_PV")
writeRaster(PV, filename = paste0(sat, path, date, '_PV', '.tif'))
removeTmpFiles(h=0.1)
}
-
Yes its single band rasters. I used the [[i]] subset since it worked for me outside the loop. Anyhow your code works better than mine and I am therefore very thankful for your help!Felix Tischer– Felix Tischer2018年09月18日 19:51:31 +00:00Commented Sep 18, 2018 at 19:51