Priya Patel
Priya Patel

Reputation: 151

The results from focal() in terra includes NAs

I'm trying to calculate focal statistics on a raster in R using the terra package. I want a 3x3 moving window and I want to calculate the max raster cell. After doing this, I turn the original and "focal stats" raster into data frames.

When I examine the dataframes, I see that the dataframe for focal stats has NA values, but the original raster had values at those cell numbers. I don't understand how this could be the case. If a 3x3 window had even one value, wouldn't that be set as the max value?

Here is the raster that I'm working with:

https://utoronto-my.sharepoint.com/:i:/g/personal/prp_patel_utoronto_ca/EQc9piU8muFLiaeobPIbCiUBwmuYGjnk-cyI3kKu95MPRg?e=Tk0GxU

Here is the code I use:

temp.ras = terra::rast('forecast_NO2_Base00_20240527_H010.tif') * 1000000000

# set the extent
terra::ext(temp.ras) <- c(-39.58222, 26.02778, -31.905, 22.005)

# set the crs
crs(temp.ras) = "+proj=ob_tran +o_proj=longlat +o_lon_p=0 +o_lat_p=31.758312 +lon_0=-92.402969 +R=6371229 +no_defs"

# here we apply focal values
temp.ras.focal = focal(temp.ras, w=3, fun = 'max', na.policy='all')

temp.df.focal = as.data.frame(temp.ras.focal, na.rm = FALSE,
                              cell = TRUE)

temp.df = as.data.frame(temp.ras, na.rm = FALSE,
                        cell = TRUE)

And here are the contents of the data frames:

head(temp.df.focal)

#>   cell focal_max
#> 1    1        NA
#> 2    2        NA
#> 3    3        NA
#> 4    4        NA
#> 5    5        NA
#> 6    6        NA

head(temp.df)

#>   cell 2[m] HTGL=Specified height level above ground; Volume Mixing Ratio (Fraction in Air) [mol/mol]
#> 1    1                                                                                     0.02893705
#> 2    2                                                                                     0.02798705
#> 3    3                                                                                     0.03773705
#> 4    4                                                                                     0.04948705
#> 5    5                                                                                     0.05238705
#> 6    6                                                                                     0.04653705

Upvotes: 1

Views: 130

Answers (1)

Eonema
Eonema

Reputation: 1320

If we count how many NAs are in temp.df.focal:

sum(is.na(temp.df.focal$focal_max))

#> [1] 2652

We see that it is the same as the number of edge cells in the raster:

sum(rep(dim(temp.ras)[1:2] - 1, 2))

#> [1] 2652

This is because focal puts NAs in the cells where the moving window goes outside the raster. To fix this, add the argument expand = TRUE to focal:

temp.ras.focal = focal(temp.ras, w=3, fun = 'max', na.policy='all', expand=TRUE)

Now the resulting data frame contiains no NAs:

sum(is.na(temp.df.focal$focal_max))

#> [1] 0

Upvotes: 1

Related Questions