I would like to calculate glcm function in R for all (52) bands in my RasterStack. Using this code:
LS<-stack(img1,img2,img3,img4,img5,img6,img7,img8,img9,img10,img11,img12,img13)
names(LS) <- paste0("B", c(1:52))
band<-brick()
for (i in 1:52){
band[i]<-glcm(LS$B1,window = c(3, 3),na_opt = 'center')
}
I get 1 layer RasterBrick with NA values and an error message: 1: In x@data@values[i] <- value : number of items to replace is not a multiple of replacement length
Do you know how to get the result for all the bands in my RasterStack?
1 Answer 1
The glcm
function outputs a stack
, with each band containing values for each of the statistics calculated. By default, all available statistics are computed.
You won't be able to put this stack
into a single band within the brick
as you are trying with band[i]<-
. This is probably what is giving you the error message.
One solution would be to output each stack
to a list
and then look at stacking them together once the loop has completed.
Something like this should work:
out <- list()
for(i in 1:dim(LS)[3]) {
out[i] <- glcm::glcm(LS[[i]], window = c(3, 3), na_opt = 'center')
}
-
Thank you, I tried to use
list
instead ofbrick
usign this codeLS<-stack(img1,img2,img3,img4,img5,img6,img7,img8,img9,img10,img11,img12,img13) names(LS) <- paste0("B", c(1:52)) band<-list() for (i in 1:52){ band[i]<-glcm(LS$B1,window = c(3, 3),na_opt = 'center') }
and it went through 52 iterations but they were all calculated for the band B1. And I also get this warningimplicit list embedding of S4 objects is deprecated
roubalma– roubalma2019年05月01日 14:10:52 +00:00Commented May 1, 2019 at 14:10 -
I'm not sure how to deal with the deprecated warning, but I have added suggested code to my answer to ensure the list contains the unique stacks.JPD– JPD2019年05月01日 14:29:33 +00:00Commented May 1, 2019 at 14:29
-
Thank you very much for your help! The code you suggested works. It helped me a lot.roubalma– roubalma2019年05月01日 17:20:01 +00:00Commented May 1, 2019 at 17:20
-
@roubalma Happy to help. Please mark the answer with the green tick if you feel it has helped with your issue.JPD– JPD2019年05月02日 13:35:22 +00:00Commented May 2, 2019 at 13:35
i
?glcm
onimg1
before stacking it with anything else? If so, do you get the same error message?glcm(LS$B1,window = c(3, 3),na_opt = 'center')
band
is astack
instead of abrick
?