Rolotoni
Rolotoni

Reputation: 43

Subset raster stack by multiple patterns in R

I'm working with some Modis and Sentinel 2 images and i have some problems subsetting raster stacks. I have a stack with some Modis images which fullfill some conditions. In these images the date is included in the name. I have extracted to a vector the date of these images.

Furthermore, i have a stack of Sentinel 2 images which also have the date in their name. I want to subset this S2 raster stack selecting only the images with the same date of the Modis images following the multiple pattern object i have extracted previously.

Here is my code

s2 <- list.files('/Users/Desktop/sentinel/16-17', pattern = '.tif')
s2stack <- stack(s2)
modis <- list.files("/Users/Desktop/modis/modisUTM", pattern = ".tif" )
modisstack <- stack(modis)
pattern_modis <- substr(modisstack, 9, 16)
s2subset <- raster::subset(s2stack, grep(pattern_modis, names(s2stack), value = T))

If i use this code it only uses the first pattern of the vector. Does anybody know how to solve it?

Thanks in advance!!!!

Upvotes: 1

Views: 662

Answers (1)

drJones
drJones

Reputation: 1233

Using the %in% operator will identify if each element in one vector is present in another vector. Be careful as the order is reversed compared to grep():

s2subset <- raster::subset(s2stack, names(s2stack) %in% pattern_modis)

Upvotes: 1

Related Questions