[R-sig-Geo] overlay() in raster package
Wearn, Oliver
oliver.wearn08 at imperial.ac.uk
Thu Feb 25 15:34:51 CET 2010
Dear all,
I'm trying to use the overlay() function in the raster package, but can't get 'if' clauses to work. Can anyone help?
I have two rasters, the first of which I would like to modify, depending on the value in the second (a forest cover raster). Specifically, if the value in the first (called ENN.500) is NA, I would like to change the value to zero, but only if the value in the forest cover raster is 1 (otherwise the value should just be left).
So, I tried:
test <- overlay(x = ENN.500,y = forest.cover,fun = function(x,y) {
if (is.na(x)) {
if (y==1) {
return(0)
}
else {
return(x)
}
}
else {
return(x)
}
})
...but I'm guessing overlay() doesn't work like this? I'm getting the following errors:
Error: object 'applymethod' not found
In addition: Warning message:
In if (is.na(x)) { :
the condition has length > 1 and only the first element will be used
I also tried:
test <- overlay(x = ENN.500,y = forest.cover,fun = function(x,y) {
if (x[is.na(x)]) {
if (y[y==1]) {
return(0)
}
else {
return(x)
}
}
else {
return(x)
}
})
...which returned the following error:
Error in .overlayList(rasters, fun = fun, filename = filename, datatype = datatype, :
cannot use this formula
The alternative would be to use arithmetic operators:
ENN.500[is.na(ENN.500] <- 0
forest.cover[forest.cover==0] <- 1
result <- ENN.500*forest.cover
...but it says in ?overlay that this is slow for very large rasters (which I will be using), so I'm guessing I should try not to use this method?
Thanks, in advance, for any help whatsoever.
Oliver
More information about the R-sig-Geo
mailing list