Reputation: 155
I am trying to read all files in a specific sub-folder of the wd
. I have been able to add a for
loop successfully, but the loop only looks at files within the wd
. I thought the command line:
directory <- 'folder.I.want.to.look.in'
would enable this but the script still only looks in the wd
. However, the above command does help create a list of the correct files. I have included the script below that I have written but not sure what I need to modify to aim it at a specific sub-folder.
directory <- 'folder.I.want.to.look.in'
files <- list.files(path = directory)
out_file <- read_excel("file.to.be.used.in.output", col_names = TRUE)
for (filename in files){
show(filename)
filepath <- paste0(filename)
## Import data
data <- read_excel(filepath, skip = 8, col_names = TRUE)
data <- data[, -c(6:8)]
further script
}
The further script
is irrelevant to this question and works fine. I just can't get the loop to look over each file in files
from directory
. Many thanks in advance
Upvotes: 1
Views: 4420
Reputation: 3448
Set your base directory, and then use it to create a vector of all the files with list.files
, e.g.:
base_dir <- 'path/to/my/working/directory'
all_files <- paste0(base_dir, list.files(base_dir, recursive = TRUE))
Then just loop over all_files
. By default, list.files
has recursive = FALSE
, i.e., it will only get the files and directory names of the directory you specify, rather than going into each subfolder. Setting recursive = TRUE
will return the full filepath excluding your base directory, which is why we concatenate it with base_dir
.
Upvotes: 1