从vector中选择目录中的文件

时间:2016-01-14 18:22:15

标签: r

如何使用list.files()仅选择在向量files中选择的文件?目录中的文件是.rds个文件。

files <- c(20388, 20389, 20390)

我试过这个,但没有回复任何东西。

list.files("Data/", pattern = paste0(files, ".rds"), full.names = TRUE)

1 个答案:

答案 0 :(得分:3)

你传递给pattern =的论点是我认为出了问题的地方。这个三步法可能会得到您想要的结果:

# Extract all .rds files
list <- list.files("Data/", pattern =".rds", full.names = TRUE)

# Define pattern for grepl
files <- c(20388, 20389, 20390)
pattern <- paste(files, sep="", collapse="|")

# Results in
pattern
[1] "20388|20389|20390" # grepl will interpret "|" as "or"

# Now we can subset list with the following
list[grepl(pattern,list)]
相关问题