mercredi 8 mai 2019

How to overlay two Rasters using ifelse (Conditional Statements) in R?

I have two rasters (images), and want to overlay them using this code:

# Getting the images
library(raster)

URL1 <- "https://www.dropbox.com/s/6jjz7ou1skz88wr/raster_1.tif?dl=1"
URL2 <- "https://www.dropbox.com/s/d5xuixohjqfnfze/raster_2.tif?dl=1"

download.file(URL1, destfile=paste0(getwd(),"/", "raster_1.tif"), method="auto", mode="wb", timeout="6000")
download.file(URL2, destfile=paste0(getwd(),"/", "raster_2.tif"), method="auto", mode="wb", timeout="6000")

# Reading the images 
raster_1 <- raster(list.files(pattern="raster_1.tif$"))
raster_2 <- raster(list.files(pattern="raster_2.tif$"))

# Overlaying
myFun <- function(x,y){ifelse(x==0 && y==0, 0, ifelse(x==1 && y==0, 2, ifelse(x==1 && y>0, y)))}

( res <- overlay(stack(raster_1 ,raster_2), fun = Vectorize(myFun) ) )

### R gives this error
Error in .overlayList(x, fun = fun, filename = filename, forcefun = forcefun,  : 
  cannot use this formula, probably because it is not vectorized

I would be very grateful if anyone could help me.

Thanks.

Aucun commentaire:

Enregistrer un commentaire