Search code examples
averager-rasterr-stars

Create a single raster file from a raster file with multiple layers and average the pixel values


I have to convert a raster file of class "stars" that contains 30 layers (30 values at each pixel) (466 x 435 x 30), to a new raster file of the same type (stars) with a single layer (466 x 435 x 1). For each pixel, its value should equal the average value of the 30 layers at the corresponding pixel. Below I am showing a screenshot of the raster file, called sim, taken from R studio

enter image description here


Solution

  • If the stars object is named r, the following expressions calculates the average per pixel (excluding NA). st_apply is used to apply the mean function over dimensions 1:2, namely the pixels.

    st_apply(r, 1:2, mean, na.rm = TRUE)
    

    Here is another example and more information:

    https://geobgu.xyz/r/raster-processing.html#pixel-means