Mann-Kendall test for a raster dataset using R

Hi!

I am new with Rstudio and I need to work with it to carry out a Mann-Kendall test.

I have a total of 620 images in a directory (folder) and I would like to get the p-value through the Mann-Kendall test.

library(sp)
library(raster)
library(Kendall)
myfolder <- 'Z:\\ArcGIS_project\\R\\IMAGES'
r_path <- file.path(myfolder, grep("STACK_KENDALL.TIF$",
list.files(file.path(myfolder),
all.files = F),
ignore.case = TRUE, value = TRUE))
mystack <- raster:stack(r_path)
#raster::layerStats(mystack, 'pearson')
fun_kendall <- function(x){ return(unlist(MannKendall(x)))}
kendall_result <- calc(mystack,fun_kendall)
writeRaster(kendall_result$tau, filename = "Z:\\ArcGIS_project\\R\\IMAGES\\STACK_tau.tif", format="GTiff", overwrite=TRUE)
writeRaster(kendall_result$sl, filename = "Z:\\ArcGIS_project\\R\\IMAGES\\STACK_p-value.tif", format="GTiff", overwrite=TRUE)

I got an error "Error in x[[1]] : subscript out of bounds" when I try to stack the raster (mystack <- raster:stack(r_path)).

Am I doing well? Does anyone know which is the issue?

Thank you so much,

Hi @barrinatxe! Welcome!

To call the stack() function from the raster package, you’d use two colons, like so:

raster::stack()

A single colon is the sequence operator.

3 Likes

Now I have a new issue (no data associated with this Raster object). Does anyone know why?

> library(sp)
> library(raster)
> library(Kendall)
> myfolder <- 'Z:\\ArcGIS_project\\R\\IMAGES'
> r_path <- file.path(myfolder, grep("STACK_KENDALL.TIF$",
+ list.files(file.path(myfolder),
+ all.files = F),
+ ignore.case = TRUE, value = TRUE))
> mystack <- raster::stack()
> #raster::layerStats(mystack, 'pearson')
> fun_kendall <- function(x){ return(unlist(MannKendall(x)))}
> kendall_result <- calc(mystack,fun_kendall)
Error in .doExtract(x, i, drop = drop) : 
  no data associated with this Raster object
> writeRaster(kendall_result$tau, filename = "Z:\\ArcGIS_project\\R\\IMAGES\\STACK_tau.tif", format="GTiff", overwrite=TRUE)
Error in writeRaster(kendall_result$tau, filename = "Z:\\ArcGIS_project\\R\\IMAGES\\STACK_tau.tif",  : 
  object 'kendall_result' not found
> writeRaster(kendall_result$sl, filename = "Z:\\ArcGIS_project\\R\\IMAGES\\STACK_p-value.tif", format="GTiff", overwrite=TRUE)

@barrinatxe In your code block here you forgot to pass your r_path variable containing the filenames to raster::stack().

Per the documentation for raster::stack(), the first argument should be the filenames.

2 Likes

Do you mean like here?

> mystack <- raster::stack(r_path)

Thank you,

Juan

Yep that should work though the section that lists your files is a little hard to decipher. You may need to add full.names=TRUE to list.files() in order to get the full file paths (instead of just the filenames).