繁体   English   中英

基于模式匹配R将列表分类为子列表

[英]Sort list into sub-lists based on pattern matching R

我在一个文件夹中有许多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')
  }
}

由于某种原因,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)
}

ps如果您在一个目录中保存了多个Landsat图像,并且希望仅按TIFF文件的图像日期列出列表(并且以后可能希望制作光栅图块),则这可能会有所帮助。

我不确定您要实现的目标,但是似乎您觉得这太困难了,并且您在快捷键<<-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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM