Home > Back-end >  How can I list.files() in subdirectories according a vector of file names?
How can I list.files() in subdirectories according a vector of file names?

Time:07-28

I have the following example:

# Vector of names
test <- c("banana", "maca")

# Directories
from.dir <- "C:/Users/Windows 10/Documents/teste"
to.dir   <- "C:/Users/Windows 10/Documents/teste2"

# Listing files and copy
files    <- list.files(path = from.dir, pattern = test, recursive = T)
for (f in files) file.copy(from = f, to = to.dir)

I have a vector of names that include two names (banana and maca); I have a directory named "teste". Inside this directory, I have 2 folders. In the first folder has an image named "banana" in the second folder has an image named "maca";

I wanna copy these two images for another directory named "teste2";

I getting an error in list.files(). It's just shown me the first name present in the first folder which is "banana". It's not shown me the name "maca", present in the second folder; In this way, I can't use the for() to copy files.

Thank's I appreciate all help

CodePudding user response:

I think you need to add an additional loop to iterate through each element in test. list.files is probably expecting a string (e.g. "banana") but instead you passed a vector

for( pattern in test){
    files    <- list.files(path = from.dir, pattern = pattern, recursive = T)
    for (f in files) file.copy(from = f, to = to.dir)
}
  • Related