I'm trying to fuzzify a Terra SpatRaster object using a Fuzzy membership function created with FuzzyR package using the method Terra::app, but the function is also applied to NA values.

FRea_0C_rast <- rasterize(FRea_0C, area_rast, "FRea_value")


FRea_0C_rast_funfuzz <- genmf("trimf", c(0, 0, 7))

FRea_0C_rast_fuzz <- app(FRea_0C_rast, FRea_0C_rast_funfuzz)


I've tried to include arguments such as na.rm but they don't work on the app function. Also, I could crop the raster to the original extent.

Is there a method to avoid the problem?

1 Answer 1


If you want to set cells in output raster r2 to NA where there's corresponding NA values in input raster r, you can do:

# test data
r = rast(matrix(1:12,3,4))
r2 = sqrt(r) # or some other processing...

r2[is.na(r)] = NA

(This is a null op for the sqrt function because sqrt(NA) = NA but I can't think of a simple example)

The computation will still be done on all cells, you just throw it away afterwards.

If the computation is expensive and you don't want to do it on NA input values at all, then take the non-NA values, work on them, then replace into the raster:

# test data
r = rast(matrix(1:12,3,4))

# square-root non-NA values
r[!is.na(r)] = sqrt(r[!is.na(r)])

Note this stomps on the original r raster, so maybe copy first:

r2 = r
r2[!is.na(r)] = sqrt(r[!is.na(r)])

where sqrt is my function. For a single layer, I think r2 = f(r1) is equivalent to r2 = app(r1, f).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.