1

I have a time series of raster images read as a raster stack using raster package in R where each raster has the calculated value ranges from 0 - 100. However, when there is cloud cover those pixels are coded as 255. I want to calculate mean of the stacked raster but exclude those pixel values in the calculation of the mean i.e. 255

The code I am using is given below and any guidance is greatly appreciated.

setwd("D:\\MODIS_data")

files_tiff <- dir(pattern = "BS")

test <- stack(files_tiff)

## Mean
rs1_mean <- calc(test, mean)
plot(rs1_mean)
user2807119
  • 333
  • 3
  • 4
  • 11
  • I wonder if you want to return a raster of mean values. I Added this in my answer. have a look – loki Jul 11 '17 at 07:31

2 Answers2

3

You could assign all 255 values as NA. By including na.rm = TRUE later, these values will be excluded from the average.

set.seed(4)
r <- raster(matrix(sample(1:255, 100, replace = T), ncol = 20))
r <- stack(r, r)
summary(getValues(r))

# layer.1         layer.2     
# Min.   :  2.0   Min.   :  2.0  
# 1st Qu.: 72.5   1st Qu.: 72.5  
# Median :145.0   Median :145.0  
# Mean   :140.2   Mean   :140.2  
# 3rd Qu.:209.5   3rd Qu.:209.5  
# Max.   :255.0   Max.   :255.0  


r[r==255] <- NA
summary(getValues(r))

# layer.1         layer.2     
# Min.   :  2.0   Min.   :  2.0  
# 1st Qu.: 72.0   1st Qu.: 72.0  
# Median :145.0   Median :145.0  
# Mean   :139.1   Mean   :139.1  
# 3rd Qu.:208.5   3rd Qu.:208.5  
# Max.   :253.0   Max.   :253.0  # <- Highest number is not 255 anymore
# NA's   :1       NA's   :1      # <- raster includes NA's now (where 255 has been)

Afterwards, raster::cellsStats() creates a mean value for each layer.

cellStats(r, mean, na.rm = TRUE)
# layer.1  layer.2 
# 139.0606 139.0606 

Edit:

If you want to return a RasterLayer with the mean of all raster layers in your RasterStack r, just write after you substituted all 255 values with NA:

mean(r)
loki
  • 9,816
  • 7
  • 56
  • 82
1

It would be helpful if you could add a reproducible example. Given your explanation your data might look the following:

# create a variable that countains 98 values between 0 - 100 and 2 times 255. 

test = c(runif(49,min = 0, max = 100),255,runif(49,min = 0, max = 100),255)

# calculating the mean without the 255 values

mean(test[-which(test==255)]) 
FAMG
  • 395
  • 1
  • 9