0

I'm doing a pretty basic aggregation operation using aggregate from the terra package. The main idea is to calculate the percentage of pixels with values over the whole number using the following function:

nofun = function(x){ length(na.omit(x))/length(x) * 100 }

Unfortunately, aggregate fails under different conditions -even simpler- and I can't figure out what I'm doing wrong.

First try: aggregate(chm, fact=20, fun=length, na.rm=T) # w/o na.rm=T

Error in FUN(X[[i]], ...) : 2 arguments passed to 'length' which requires 1

Second try:

aggregate(chm, fact=20, fun=function(x){ length(x) } )

Error: [aggregate] this function does not return the correct number of values

Same result applying the above-mentioned final function modified according to this reply, as follows:

function(x){ if(any(is.numeric(x))){length(na.omit(x))/length(x) * 100} else {NA_real_}}

Everything tested both in terra 1.4.22 and 1.5.12 on W10.

Nico
  • 191
  • 1
  • 6

1 Answers1

0

Example data

library(terra)
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)

You can compute the percentage of cells that are not NA with a simple aggregate function

a <- aggregate(!is.na(r), 2, mean) * 100 

Or, more efficiently

a <- aggregate(is.finite(r), 2, mean) * 100 

But this also seem to work fine with your function

nofun <- function(x){ 100 * length(na.omit(x)) / length(x)}
b <- aggregate(r, 2, nofun)
plot(b, plg=list(title="NA (%)"))

enter image description here

By adding na.rm=TRUE you provide an additional argument to length that it does not have. It only has one argument x.

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • you're right: I thought `na.rm` was relaed to the main function and not `length`. thanks! I found out that the error `[aggregate] this function does not return the correct number of values` lied in the fact that I was using `fact=gridRes/res(chm)[1]` to create the aggregation factor. Unfortunately `res(chm)` was 1.034m and this led to `fact=19.xxx` instead of the desired `20` (that I avoided in the example above in order n to use undeclared variables). – Nico Jan 14 '22 at 09:06