0

I'm trying to plot the results from cor function that is running over multiple subfolders that contain TIF files. The process I have followed so far didn't work. It seems there is a problem while running the sampleRandom function but I cannot figure out what is the problem. Below is the code and then the error message

# define root folder 
setwd("./Bajio")
# list of sulfoders 
subf<-list.dirs(full.names=FALSE, recursive=FALSE)
# define outpath 
outpath <- "./Bajio_mes"
#create output directory
dir.create(outpath)
# define the output names
outfiles <- paste0(outpath, subf)
# define the output format
extension(outfiles) <- 'jpeg'
#running the for loop
for(j in 1:length(subf)){
    print(subf[j])
    h <- list.files(path=subf[j], recursive=TRUE, full.names=TRUE,pattern='.tif')
    print(h)
    d <- brick(h)
    e <- cor(sampleRandom(d[],size= ncell(d) * 0.5 ), method = "pearson")
    f <- corrplot(e, method = "number",col= colorRampPalette(c("black","pink", "red"))(10))
    f<-jpeg(f,outfiles[j]
    }

After running the code I obtain the following:

Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘sampleRandom’ for signature ‘"matrix"’

How can I solve this problem?

2

sampleRandom needs the whole brick (or raster) fed to it, you are feeding it the vector of values with d[].

Reproducing your error, minimally:

> r1 =raster(matrix(1:12,3,4))
> r2 =raster(matrix(1:12,3,4))
> b = brick(r1,r2)
> sampleRandom(b[], 5)
Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘sampleRandom’ for signature ‘"matrix"’

Sampling from the brick:

> sampleRandom(b, 5)
     layer.1 layer.2
[1,]      10      10
[2,]       8       8
[3,]       1       1
[4,]       7       7
[5,]       4       4
2
  • You're right it has to work with the whole brick. I've made the change but then I obtain the following error Error in switch(units, in = res, cm = res/2.54, mm = res/25.4, px = 1) * : non-numeric argument to binary operator It seems more related to exporting the jpeg but even if a change the margins and other variables it hadn't work. Do you have any idea on that? Nov 1 '20 at 18:32
  • I've got you past your first error - could you mark this as answered and then ask about the next error? Do some diagnostics first - like working out which function call is breaking - and then post it up.
    – Spacedman
    Nov 1 '20 at 21:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.