0

I am adapting a function written by another user here, wherein a series of raster files can be batch cropped. The function was originally written for .asc files, however I intend to use it for .tif files, which were produced en masse using pyModis (python package; not super relevant).

Right now, filenames under the original list.file() function is:

 [1] "./FILE_mosaik_DOY.tif"      "./FILE_mosaik_DOY.tif.xml" 
 [3] "./FILE_mosaik_EVI.tif"      "./FILE_mosaik_EVI.tif.xml" 
 [5] "./FILE_mosaik_NDVI.tif"     "./FILE_mosaik_NDVI.tif.xml"
 [7] "./FILE_mosaik.tif"          "./FILE_mosaik.tif.xml"     
 [9] "./FILE_mosaikb.tif"         "./FILE_mosaikb.tif.xml"    
 [11] "./ReferenceRaster.tif"

I want for it to be:

 [1] "./FILE_mosaik_DOY.tif"      "./FILE_mosaik_EVI.tif" 
 [3] "./FILE_mosaik_NDVI.tif"     "./FILE_mosaik.tif"
 [5] "./FILE_mosaikb.tif"         "./ReferenceRaster.tif"      

The original code uses the following line to bring define the files that will be cropped in a batch:

  filenames <- list.files(pattern="*.asc", full.names=TRUE)   #Extract list of  file names from working directory

However because I want to use tif files instead, I am using the line below.

  filenames <- list.files(pattern="*.tif", full.names=T)   #Extract list of  file names from working directory

EXCEPT: There are also .xml files in my working directory that include a .tif extension. Therefore, filenames includes such files as "./FILE_mosaik_EVI.tif.xml". I want to include only the tif files in filenames.

I have tried to remove the .xml files two ways. First, I attempted to use rm(), however because filenames is a character and not a list (at least I think this is the reason) things didn't work out right and I ended up with a NULL filenames object.

  filenames <- list.files(pattern="*.tif", full.names=T)   #Extract list of  file names from working directory
  filenames <- rm(pattern="*.xml", list=filenames) #Remove the .xml files automatically produced in pyModis

I also tried to specify that I don't want .xml files in the original argument

  filenames <- list.files(pattern="*.tif" && !="*.txt", full.names=T)   #Extract list of  file names from working directory

but that didn't work either. Unfortunately, many of the existing questions on stackoverflow deal with list.files() failing to find enough files, rather than too many...

How can I achieve a filenames object that includes only the .tif files?

Community
  • 1
  • 1
JepsonNomad
  • 187
  • 2
  • 15

1 Answers1

4

You can use $ sign to specify end of the string:

filenames <- list.files(pattern="\\.tif$", full.names=T)
HubertL
  • 19,246
  • 3
  • 32
  • 51