I am trying to create a new raster from one existing raster using conditional logic, ifelse statements. The existing raster has numeric values and NA values. Here is what I tried so far, based on other posts within Stack Exchange:

f <- function(phos_all) {
        ifelse(is.na(phos_all) | NA, 
            ifelse(phos_all>=4) & (phos_all<10), 20,

phos_fert_2.5 <- calc(phos_all, fun = f, na.rm = TRUE)

When I run this code I get the following error:

Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) : cannot use this function. Perhaps add '...' or 'na.rm' to the function arguments?

  • What do you mean with is.na(phos_all) | NA? This is saying the same thing (NA == TRUE or NA) and there is no resulting condition. You can deal with elements that do not meet any condition by having the last condition in the nested ifelse statments be NA, which would include existing NA values. Commented Nov 4, 2019 at 18:13

1 Answer 1


I would start with your ifelse statement. You have is.na(phos_all) | NA stating the condition [NA == TRUE or NA] which is redundant and can be dealt with at the end if the ifelse. You also have some misplaced/unnecessary parenthesis.

Let's clarify the f reclassification function a bit.

f <- function(x, ...) { 
    ifelse(x <= 4, 30,
      ifelse(x >= 4 & x < 10, 20,
        ifelse(x >= 10, 0, NA )))

Now we can test it on a vector to make sure it is yielding expected results.

y <- round(runif(100, 0, 20))
  y[c(2,50,90)] <- NA 

We can now roll it into a raster example. Note that I did add a ... argument into the f function. This can sometimes help calc and overlay with passing the function.

r <- raster(nrow=100, ncol=100)
  r[] <- round(runif(ncell(r), 0, 20)) 

( rrc <- calc(r, fun = f) )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.