I have a RasterStack with 191 layers with the following naming convention:
[1] "LC08_L1TP_037035_20130501_20170310_01_T1_sr_ndvi" "LC08_L1TP_037035_20130602_20170310_01_T1_sr_ndvi"
...
I also have a separate data.frame (df_filtered) that contains a list of these rasters after a set of filtering conditions were applied, resulting in 161 rasters. The file names listed in df_filtered, however, have a slightly different naming convention, where the last part ("_sr_ndvi") of the file name was dropped:
ID
1 LC08_L1TP_037035_20130501_20170310_01_T1
2 LC08_L1TP_037035_20130602_20170310_01_T1
I would like to subset the original stack of 191 rasters to only include those listed in df_filtered. My approach was to use use grep to conduct a partial match. Here is the code I tried:
rasters_filtered <- raster::subset(my_stack, grep(df_filtered$ID, names(my_stack), value = T))
This works for the first raster in the stack, but not for the rest. Here is the error: "argument 'pattern' has length > 1 and only the first element will be used"
Is there a way to have it iterate through all the names in the list?