检查 R 中是否存在带通配符扩展的文件

Check for existence of file with wildcard-expansion in R

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

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

问题: 如果我将 file.exists 函数应用于 Sys.glob 函数,它将始终 return 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] TRUE TRUE

我希望结果是

[1] TRUE FALSE TRUE

因为没有 test2 文件夹。

所以我基本上只想在 file.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))