Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrong values computed by terra::median if SpatRaster has more than 3 layers #970

Closed
MatteaE opened this issue Jan 10, 2023 · 1 comment
Closed

Comments

@MatteaE
Copy link

MatteaE commented Jan 10, 2023

Hi all

Trying to combine multiple layers of a SpatRaster with the median() function, the resulting grid has some wrong (seemingly semi-random?) values, as soon as the original SpatRaster has more than 3 layers.

Minimal example: terra_median_bug.zip

Result on my system: terra_median_bug

R 4.1.2, terra 1.6.47 on Ubuntu 22.04.01.

@rhijmans
Copy link
Member

Thank you for reporting this. This is a bug in the CRAN version but it works correctly in the development version of "terra", With that version I get:

library(terra)
#terra 1.5.48
lf <- list.files(pattern = "\\.tif$")
r <- rast(lf)

Three ways to compute the median

# built in
x <- median(r)
y <- app(r, median)
# "manual"
z <- app(r, \(i) median(i))

Compare

s <- c(x,y,z)
diff(s)
#class       : SpatRaster 
#dimensions  : 13, 13, 2  (nrow, ncol, nlyr)
#resolution  : 80, 80  (x, y)
#extent      : 717180, 718220, 4392180, 4393220  (xmin, xmax, ymin, ymax)
#coord. ref. : WGS 84 / UTM zone 42N (EPSG:32642) 
#source(s)   : memory
#names       : median, median 
#min values  :      0,      0 
#max values  :      0,      0 

Cell 6 had the largest difference, but it is good now.

r[6]
#  North/South North/South North/South North/South North/South North/South
#1   -5.855352    -4.82694    2.915545    3.260163   -109.9052  -0.2166536
#  North/South North/South North/South North/South
#1     4.42027   -3.505593    1.284746   -1.696935
s[6]
#      median     median     median
#1 -0.9567944 -0.9567944 -0.9567944

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants