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

focal3D is not computing correct values #1057

Closed
flaviomoc opened this issue Mar 8, 2023 · 3 comments
Closed

focal3D is not computing correct values #1057

flaviomoc opened this issue Mar 8, 2023 · 3 comments

Comments

@flaviomoc
Copy link

flaviomoc commented Mar 8, 2023

Dear Robert,

When applying the focal3D function, I noticed that the values on the right end (east side) of the raster are lower than they should be. Also, when using na.policy = "omit", it is returning an error even though there are no NAs in the raster.

I would appreciate it if you could help.

Here is an example code:

r <- terra::rast(ncol = 10, nrow = 10, nlyr = 11)
values(r) <- 1:ncell(r)

test <- terra::focal3D(r, c(3, 3, nlyr(r)), function(x) {
  min(x, na.rm = TRUE)
}, na.policy = "all")

plot(test)

test <- terra::focal3D(r, c(3, 3, nlyr(r)), function(x) {
  min(x, na.rm = TRUE)
}, na.policy = "omit")
# Error: [writeValues] incorrect number of values (too few) for writing
@rhijmans
Copy link
Member

rhijmans commented Mar 9, 2023

I understand why you think it is wrong but the values on the right side are correct, I think. Your data are global lon/lat, so you need to consider that the right-most column is adjacent to the left-most column. So the low values in the fist column affects to results. This is not the case with any other crs.

r <- terra::rast(ncol = 10, nrow = 10, nlyr = 11, crs="local")
values(r) <- 1:ncell(r)
test <- terra::focal3D(r, c(3, 3, nlyr(r)), mean, na.rm=TRUE)

But you were of course right that the na.policy argument did not work and thank you for reporting that. This now works:

test <- terra::focal3D(r, c(3, 3, nlyr(r)), fun=min, na.rm = TRUE, na.policy = "omit")

@flaviomoc
Copy link
Author

Hi Robert,

Thank you very much for your quick response. I understood that the calculation was correct.

Regarding the argument na.policy = "omit", I got another error when simulating a raster cell with NA.

r <- terra::rast(ncol = 10, nrow = 10, nlyr = 11, crs="local")
values(r) <- 1:ncell(r)
r[5] <- NA
test <- terra::focal3D(r, c(3, 3, nlyr(r)), fun=min, na.rm = TRUE, na.policy = "omit")
# Error in vout[k] <- vv[k] : replacement has length zero

@rhijmans
Copy link
Member

rhijmans commented Mar 9, 2023

Fixed. Thanks again!

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