Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count NAs using terra's global function?

Tags:

r

na

raster

terra

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

like image 362
ia200 Avatar asked Apr 22 '26 08:04

ia200


2 Answers

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)
like image 139
AndrewGB Avatar answered Apr 23 '26 21:04

AndrewGB


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
like image 29
Quinten Avatar answered Apr 23 '26 22:04

Quinten