Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select raster layers from raster stack based on certain pattern on raster layer's name

Tags:

stack

r

r-raster

I have a raster stack in r that contains 499 layers. Each layer has a specific name pattern.

[1] "Sacharovi_PA1_RUN1_GAM"               "Sacharovi_PA1_RUN1_GLM"              
[3] "Sacharovi_PA1_RUN1_RF"                "Sacharovi_PA1_RUN1_CTA"              
[5] "Sacharovi_PA1_RUN1_MAXENT.Phillips"   "Sacharovi_PA1_RUN2_GAM"              
[7] "Sacharovi_PA1_RUN2_GLM"               "Sacharovi_PA1_RUN2_RF"               
[9] "Sacharovi_PA1_RUN2_CTA"                 

What I want to do is save each model (GAM, RF, GLM, CTA, MAXENT) to a different stack. How can I select the models I want (all models containing the word "GAM"/"GLM"/"RF" etc.)?

Until now i have tried to do a subset of the raster stack as such:

  result <- subset(my_stack, grep("GAM"))

but will not work. Could you please help me on that?

like image 574
Tatus Avatar asked Oct 15 '25 15:10

Tatus


1 Answers

You don't appear to have finished the grep properly - you have to tell it to search through the names, see below. Also be sure that you're accessing the correct function by specifying the raster package. Subset is a very generic function name and it might have been trumped by another library you have added after raster - or R will default to base::subset if you haven't loaded the library at all.

I also prefer to use value = TRUE for debugging, although it will work either way.

all_GAM <- raster::subset(my_stack, grep('_GAM', names(my_stack), value = T))
like image 161
obrl_soil Avatar answered Oct 17 '25 07:10

obrl_soil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!