0

I am trying to calculate a 72 bands raster. If the first 36 bands value (near infrared band) is greater than the latter 36 bands value (shortwave infrared band), assign it 0; if not then proceed on the following function. I tried other ways of writing it (basically the same logic) and the same errors show up. This is the function I wrote:

raster_stack <- stack("NIR.bin", "SWIR.bin")
#ndii = NIR - SWIR/NIR+SWIR

fun <- function(x) {
       x[is.na(x)] <- 0;
       if (x[37:72] >= x[1:36]){
           0} else {
               ndii <- ((x[1:36]-x[37:72]) / (x[1:36]+x[37:72]));
               silent=TRUE;
               return(ndii)
              }
}
ndii <- calc(raster_stack, fun)

The error message is always this one:

Error in setValues(out, x) : values must be numeric, integer, logical or factor

I added x[is.na(x)] <- 0 to get rid of the NA value, but it seems that it does not help. Any insights on solving this?

Yuyun He
  • 5
  • 1
  • 3
  • I think you need to clean up the function. What is `nd` ? The command `silent = TRUE` will never be executed since it comes after the `return(nd)` line. You might want to check out this link [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) – steveb May 09 '16 at 15:02
  • Sorry for the confusion. "nd" refers to ndii value that this function is calculating. Any insights? I tried to write for loops but it does not help either. – Yuyun He May 09 '16 at 15:52
  • @YuyunHe are you sure you can stack binary files that way? – Geo-sp May 09 '16 at 21:09

1 Answers1

0

There are a couple of issues. Your if statement is not good, as you are comparing 36 values. Also, you need to treat the data like a matrix.

library(raster)
raster_stack <- stack("NIR.bin", "SWIR.bin")
#ndii = NIR - SWIR/NIR+SWIR

fun <- function(x) {
    y <- (x[,1:36]-x[,37:72]) / (x[,1:36] + x[,37:72])
    i <- x[,37:72] >= x[,1:36]
    y[i] <- 0
    y
}
ndii <- calc(raster_stack, fun)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63