I can iterate over all the files in a directory. However, I want to iterate over certain files instead of all the files. I want to use indices.
I want to do this by using a file_id
vector. Each vector element would be index in "files".
For example: I have 500 total files in a directory, and I only want to iterate three files which are files 2,4,15. I generated a vector called file_id = c(2, 4, 15)
. Now, how can I iterate over only these files or indices, such as files[2]
, files[4]
, files[15]
which will get data only from files 2, 4, and 15, instead of all 500 files.
#get a list of all the files in directory.
files <- list.files(directory, full.names = TRUE)
#iterate over all the files in directory, and get file data
for (item in files){
filedata <- read.csv(item)
}
#What I want to do is only iterate over following files indicated in file_id vector. That will open files 2,4, and 15 nothing else.
file_id = c(2, 4, 31)