Reputation: 7435
How would I use list.files()
to select only those files that are selected in a vector files
? The files in the directory are .rds
files.
files <- c(20388, 20389, 20390)
I've tried this, but not returning anything.
list.files("Data/", pattern = paste0(files, ".rds"), full.names = TRUE)
Upvotes: 0
Views: 1172
Reputation: 24188
The argument you're passing to pattern =
is where things are going wrong I believe. This three-step approach might get you the desired result:
# 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)]
Upvotes: 3