NEXUSAG
NEXUSAG

Reputation: 53

Select file from the list of the folder

I have a multiple folder with files name in numeric (12345.in). I am trying to write a function which will list the nearest file if the file in the command is not in the folder

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

Upvotes: 0

Views: 91

Answers (1)

M. Schumacher
M. Schumacher

Reputation: 150

I would try to extract the number of each file and check for the nearest value:

 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")

You can also put everything into one pipe:

 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")

Of course, you can also translate this approach into a function.

Edit: If you have all the files in different folders, you can use this approach:

 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)")

Upvotes: 1

Related Questions