How to count NAs using terra's global function?
Asked Answered
N

2

7

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

Neidaneidhardt answered 4/4, 2022 at 17:29 Comment(0)
L
7

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)
Louralourdes answered 4/4, 2022 at 18:11 Comment(0)
G
4

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
Grissel answered 4/4, 2022 at 17:43 Comment(4)
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?Neidaneidhardt
@Neidaneidhardt 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").Louralourdes
I'm on 1.4.22 so I'll try updating to see if that solves the issue.Neidaneidhardt
Thanks @AndrewGB, that did solve the issue. If you post an answer I'll accept it.Neidaneidhardt

© 2022 - 2024 — McMap. All rights reserved.