4

I am trying to count the non-NA values in a spatRaster using the global() function from the terra package. All the functions (mean, max, sd, etc.) seem to work except for "isNA" and "notNA". For these two functions it returns this error: Error in fun(values(x[[i]]), ...) : could not find function "fun", which is the same error it returns for a misspelled/non-existent function.

r <- rast(ncols=10, nrows=10)
values(r) <- c(1:(ncell(r)-1),NA) # Add one NA value
global(r, fun="mean", na.rm=TRUE) # works
global(r, fun="notNA") # error
global(r, fun="notAfunction") # error

Interestingly, when looking at the documentation (?global), the NA functions are named in the function description but are not listed specifically listed as argument options for fun.

So can global() count the NAs/non-NAs? Are the NA function names correct?

Edit: terra version: 1.4.22

ia200
  • 255
  • 1
  • 9

2 Answers2

5

Your version of terra is likely outdated and does not include the functions isNA or notNA. You can see the functions in the source code of the current version at Terra raster methods (lines 2551 to 2639 for the global function).

I am currently running version 1.5.21, and the functions work fine.

packageVersion("terra")
#[1] ‘1.5.21’

global(r, fun="isNA")
#      isNA
#lyr.1    1

global(r, fun="notNA")
#      notNA
#lyr.1    99

You can update the package and reload the library with the following:

install.packages("terra")
library(terra)
AndrewGB
  • 16,126
  • 5
  • 18
  • 49
2

When I run your code, it actually works:

library(terra)
r <- rast(ncols=10, nrows=10)
values(r) <- c(1:(ncell(r)-1),NA) 
global(r, fun="mean", na.rm=TRUE)
global(r, fun="isNA")
global(r, fun="notNA")

Output of isNA:

      isNA
lyr.1    1

Output of notNA:

      notNA
lyr.1    99
Quinten
  • 35,235
  • 5
  • 20
  • 53
  • That is odd. I just copied and ran the code from what you posted to double check and I'm still getting errors for the two NA functions but the mean works fine. Any ideas what the difference might be? – ia200 Apr 04 '22 at 18:00
  • 1
    @ia200 What version of `terra` are you running? Maybe you have an outdated version that doesn't include those functions? It works for me too, when running version `1.5.21`. To check your version, you can run `packageVersion("terra")`. – AndrewGB Apr 04 '22 at 18:03
  • 1
    I'm on 1.4.22 so I'll try updating to see if that solves the issue. – ia200 Apr 04 '22 at 18:05
  • Thanks @AndrewGB, that did solve the issue. If you post an answer I'll accept it. – ia200 Apr 04 '22 at 18:08