'Get mean NDVI inside 95% percentile

I'd like to get NDVI average data from COPERNICUS/S2_SR collection by date using rgee package. I don like to extract the NDVI mean with all values inside my ROI, but inside the interval 5th percentile and 95th NDVI values.

I try to do:

# Packages
library(tidyverse)
library(rgee)
library(sf)
ee_Initialize(drive=TRUE)

# Function for remove cloud and shadows ------------------------------------------
getQABits <- function(image, qa) {
  # Convert decimal (character) to decimal (little endian)
  qa <- sum(2^(which(rev(unlist(strsplit(as.character(qa), "")) == 1))-1))
  # Return a single band image of the extracted QA bits, giving the qa value.
  image$bitwiseAnd(qa)$lt(1)
}
s2_clean <- function(img) {
  # Select NDVI
  img_band_selected <- img$select("B[4|8]")
  
  # quality band
  ndvi_qa <- img$select("QA60")

  # Select pixels to mask
  quality_mask <- getQABits(ndvi_qa, "110000000000")
  
  # Mask pixels with value zero.
  img_band_selected$updateMask(quality_mask)

  # Compute NDVI 
  img_band_selected <- img_band_selected$select("B8")$subtract(img_band_selected$select("B4"))$divide(img_band_selected$select("B8")$add(img_band_selected$select("B4")))
}


# Define a Region of interest
roi <-ee$Geometry$Point(-52.19032,-30.25413)$buffer(500)

# Sentinel-2 MSI dataset into the Earth Engine’s public data archive ------------              
s2 <- ee$ImageCollection("COPERNICUS/S2_SR")

# Select S2 images ---------------------------------------------------------------
s2_roi  <- s2$
  filterBounds(roi)$
  filter(ee$Filter$lte("CLOUDY_PIXEL_PERCENTAGE", 1))$
  filter(ee$Filter$date(as.character(as.Date("2019-12-04")), as.character(as.Date("2020-05-03"))))$
  map(s2_clean)

s2_roi_add_area <- s2_roi$map(
  function(img) {
    img$set("area", img$clip(roi)$geometry()$area())
  }
)

#Extract average NDVI values 
ee_mean_ndvi<- ee_extract(
 x = s2_roi_add_area,
 y = roi,
 scale = 10,
 fun = ee$Reducer$mean(),
 via = "drive"
)
ee_mean_ndvi

I didn't find any way for combining ee$Reducer$mean() and ee$Reducer$percentile(95) in the same ee_extract function. Please, any help with it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source