我在一个文件夹中有许多TIFF文件(每个文件都属于一个图像日期),并希望列出尽可能多的唯一日期,然后用适当的文件填充这些列表。理想情况下,我希望有一个函数,用户可以只对日期列表进行更改,尽管我无法运行可以遍历日期列表的函数。相反,我尝试创建一个函数,并在每个唯一的日期运行它。
dates <- list('20180420', '20180522', '20180623', '20180725', '20180810')
# Make a list of all files in the data directory
allFilesDataDirectory <- list.files(path = dataDirectory, pattern = 'TIF$')
# allFilesDataDirectory is a list of 60 TIFF files with the same naming convention along the lines of LC08_L1TP_038037_20180810_20180815_01_T1_B9
allDateLists <- NULL
for (d in dates){
fileFolderDate <- NULL
dynamicDateNames <- paste0('fileListL8', d)
assign(dynamicDateNames, fileFolderDate)
allDateLists <- c(allDateLists, dynamicDateNames)
}
myFunction <- function(date, fileNameList){
# files first
for (i in allFilesDataDirectory){
# Create a list out of the file name by splitting up the name wherever there is a _ in the name
splitFileName <- unlist(strsplit(i, "[_]"))
if(grepl(splitFileName[4], date) & (grepl('B', splitFileName[8]))){
fileNameList <- c(fileNameList, i)
print(i)
}
else {
print('no')
}
}
}
myFunction(date = '20180623', fileNameList = 'fileListL820180623')
该函数运行,但是fileListL820180623为NULL。
当对此进行硬编码时,一切正常,不确定是否有区别。我尝试使用assign()(此处未显示),但没有执行任何操作。
for (i in allFilesDataDirectory){
# Create a list out of the file name by splitting up the name wherever there is a _ in the name
splitFileName <- unlist(strsplit(i, "[_]"))
if(grepl(splitFileName[4], '20180623') & (grepl('B', splitFileName[8]))){
fileListL820180623 <<- c(fileListL820180623, i)
}
else {
print('no')
}
}
答案 0 :(得分:0)
由于某种原因,grepl在这种情况下无法正常运行,但是glob2rx的运行效果很好。
dates <- list('20180420', '20180522', '20180623', '20180725', '20180810')
for (d in dates){
listLandsatFiles <- list.files(path = dataDirectory, pattern = glob2rx(paste0('*', d, '*B*TIF')))
files
dynamicFileListName <- paste0('fileListL8', d)
assign(dynamicFileListName, listLandsatFiles)
}
p.s。如果您在一个目录中保存了多个Landsat图像,并且希望仅按TIFF文件的图像日期列出列表(并且以后可能希望制作光栅图块),则这可能会有所帮助。
答案 1 :(得分:0)
我不确定您要实现什么目标,但是似乎您太过困难了,并且您在快捷键<<-
和assign
上使用了错误的选择(在极少数情况下,保证使用)。
我会根据以下建议提出建议:
getTiffPattern <- function(pattern='', folder='.') {
ff <- list.files(folder, pattern = pattern, full=TRUE)
grep('\\.tif$', ff, ignore.case = TRUE, value=TRUE)
}
getTiffPattern('20180420')
或者是日期向量
dates <- list('20180420', '20180522', '20180623', '20180725', '20180810')
x <- lapply(dates, getTiffPattern)