首页 > 解决方案 > 从文件夹列表中选择文件

问题描述

我有一个文件名为数字(12345.in)的多个文件夹。我正在尝试编写一个函数,如果命令中的文件不在文件夹中,它将列出最近的文件

soili=371039 #this is the file name

Getmapunit <- function(soili){
  soilfile=list.files(pattern = paste0(soili,".in"), recursive = TRUE)
  if (length(soilfile)==0){
    soilfile=list.files(pattern = paste0(soili+1,".in"), recursive = TRUE)
  }
  soilfile
}
soilfile=Getmapunit(soili)

#i want to extract the file name closest to 371039, i was able to write function to get file name with next number

标签: r

解决方案


我会尝试提取每个文件的数量并检查最接近的值:

 library(magrittr) 
 library(stringr)
 soili <- 371039

 # get all files in the specific folder
 files <- list.files(path = "file folder", full.names = F) 

 # extract number of each file and turn it into an integer  
 numbers <- str_extract(files, ".*(?=.in") %>% as.integer()

 # get the number of the nearest file
 nearest_file <- numbers[which.min(abs(soili - numbers)]

 # turn it into a filename
 paste0(as.character(nearest_file), ".in")

您还可以将所有内容放入一个管道中:

 soili <- 371039
 nearest_file <- list.files(path = "file folder", full.names = F) %>%
                      str_extract(files, ".*(?=.in") %>% 
                      as.integer() %>%
                      .[which.min(abs(soili - .)] %>%
                      paste0(as.character(nearest_file), ".in")

当然,您也可以将这种方法转换为函数。

编辑:如果你有不同文件夹中的所有文件,你可以使用这种方法:

 soili <- 371039
 files <- list.files(path = "highest_file_folder", full.names = T)
 nearest_file <- files %>%
                  str_extract(., "[^/]*$") %>% 
                  str_extract(".*(?=.in)") %>%
                  as.integer() %>%
                  .[which.min(abs(soili - .)] %>%
                  paste0(as.character(nearest_file), ".in")

 # getting filepath with nearest_file out of the files vector
 files[str_detect(files, nearest_file)]

 # little example
 files <- c("./folder1/12345.in", "./folder2/56789.in") %>% 
   str_extract(., "[^/]*$") %>% 
   str_extract(.,".*(?=.in)")

推荐阅读