How to perform raster calculation in R

6k Views Asked by At

I am processing radiometry rasters. I wrote two bands in two separate files already:

setwd("D:/All_radio")
writeRaster(new,filename="NIR.envi",format="ENVI",overwrite=T)
writeRaster(new1,filename="SWIR.envi",format="ENVI",overwrite=T)

When I tried

ndii<-(("NIR.envi"- "SWIR.envi")/("NIR.envi"+ "SWIR.envi"))

the error occurs as "non-numeric argument to binary operator" How can I turn raster into numeric argument?

1

There are 1 best solutions below

2
On BEST ANSWER

You may need something like calc from the raster package.

 rast_stack <- stack(NIR.envi,SWIR.envi)
 fun <- function(x) { (x[1]-x[2])/(x[1]+x[2])}
 ndii <- calc(rast_stack, fun)

but there appear to be a few issues with your code anyway. In this line you are using strings rather than the rasters as variables.

(("NIR.envi"- "SWIR.envi")/("NIR.envi"+ "SWIR.envi"))

and you appear to be trying to create both rasters with the same data, in which case your output would always be 0. You are also creating a raster file but not creating an object in r.