r - 从文件夹列表中选择文件
问题描述
我有一个文件名为数字(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
解决方案
我会尝试提取每个文件的数量并检查最接近的值:
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)")
推荐阅读
- python - 我无法访问另一个类中的变量
- c# - 复制的样式为空。改用 StyleNotFound
- twitter-bootstrap - 使用 Bootstrap 4 Flexbox 居中导航项目
- playback - 私有 Android 应用程序未显示在托管 Android Google Play 中
- r - 为什么 dnorm() 不返回我在执行 sd(dnorm()) 时输入的标准差?
- python - 使用kivy和python制作android apk时如何使用request之类的模块?
- mongodb - Stitch Facebook 身份验证返回“AuthError”
- python - 如何将列表中的字符串连接到字符串所引用的对象
- android - 如何在 Rider IDE 中为 Xamarin Android 应用程序设置可绘制资源文件夹
- python - 使用 pip 在 Windows 上安装 pyaudio 模块