首页 > 解决方案 > 在 R 中检查是否存在带有通配符扩展的文件

问题描述

我想根据变量中的字符串值检查文件夹是否存在。

我需要使用通配符功能,因为我要检查的文件夹名称可能不同,但始终包含字符串变量的内容

问题:如果我将file.exists函数应用于Sys.glob函数,它将始终返回TRUE,因为Sys.glob我将其用于通配符扩展)只会对实际存在的文件起作用,而跳过不存在的文件。

想象一下我的有两个文件夹path_root

path_root/hihi_test1_hoho

path_root/haha_test3_hehe

variable <- c("*test1*", "*test2*", "*test3*")

file.exists(
Sys.glob(
file.path(path_root, variable)))

在示例中,输出将是

[1] 对对对

我希望结果是

[1] 真假真

因为没有test2文件夹。

所以我基本上只想在file.exists函数中使用通配符扩展,但我无法让它工作。

标签: rwildcardfile-exists

解决方案


重新阅读问题,现在对所需内容有了更好的了解,请尝试:

path_root <- "C:/Users/User/Documents"
variable <- c("somepattern.*", ".*R")
#Search for pattern in directories:
grepl(paste(file.path(path_root, variable), collapse = "|"), list.dirs(path_root, full.names = TRUE, recursive = FALSE))

推荐阅读