# How to address NA in pixel regression (local computation) with R terra package

For example, I have five NDVI TIFFs and five precipitation TIFFs. I used the code provided by Robert (https://stackoverflow.com/questions/63831287/extracting-p-values-from-lineair-regression-on-raster-image-through-calc-functio?rq=1) as a reference, but it had the following error.

``````library(terra)
f1 <- rast(dir("D:/test",
pattern = '.tif\$',full.names = T))
f2 <- rast(dir("D:/test1",
pattern = '.tif\$',full.names = T))
f <- c(f1,f2)

fun <- function(x) {
if (all(is.na(x))) {
return(c(NA, NA))
}
m <- lm(x[1:5] ~ x[6:10])
summary(m)\$coefficients[,4]
}
x1 <- app(f, fun,cores=8)
``````

The error is:

``````***Error in checkForRemoteErrors(val) :
18 nodes produced errors; first error: 0 (non-NA) cases***
``````

I think it is likely that NA values cause it. And I try to modify it to this from a reference:

``````fun_linear = function(x){
if(length(na.omit(x))<10) return(c(NA, NA, NA))  #remove the time series that contain NA
lmdt = lm(x[1:5] ~ x[6:10])
a1 = summary(lmdt)
slope = a1\$coefficients[2]
intercept = a1\$coefficients[1]
pvalue = a1\$coefficients[8]
return(c(slope, intercept, pvalue))
}
pixellinear = app(f, fun_linear, cores=8)
``````

It succeeded!

But I still can't figure out why it reports an error in the first method.

1. Why `if(length(na.omit(x))<10) return(c(NA, NA, NA))` return 3 NA instead of 10 NA(5 NDVI tifs + 5 precipitation tifs)?

2. Why

if (all(is.na(x))) { return(c(NA, NA))

return 2 NA instead of 12 NA?

(In this example,Robert create 12 layers:https://stackoverflow.com/questions/63831287/extracting-p-values-from-lineair-regression-on-raster-image-through-calc-functio?rq=1)

1. In my limited experience with terra::app and raster::calc , I think x is like a time series across z axis (while x axis is longitude, y axis is latitude). As the description of app in terra document (pdf version from cran),the raster data is represented as either a matrix in which each layer is a column, or a vector representing a cell. So,the if statement in the function is hard to comprehend for me.

x <- c(1,2,NA) y <- c(1,2,3) z <- c(NA,NA,NA) all(is.na(x)) all(is.na(y)) all(is.na(z))

I create this example, and only `all(is.na(z))` returns `TRUE`. What if this situation?

``````library(terra)
r=rast(nrows=10,ncols=10,vals=1:100)
s1 <- lapply(1:10, function(i) setValues(r, rnorm(ncell(r), i, 3)))
files <- rast(s1)
files[[1]][1,1] <- NA
files[[3]][1,1] <- NA
files[[5]][1,1] <- NA
``````

I create a ten layers spatraster which its first third fifth layer are set NA of [1,1].Then using terra::app function to do something(eg:trend,regression,correlation),the first thing to do is remove the pixel that contain NA.So my confusion and problems arose.

I am searching for a long time on net. But no use. How can I do this?