how can I import csv files according to their column names instead of their file names? Let's say i have 2 different csv files in my working directory. One of the files names is "interesting.csv" with column names as follows: "interesting1" "interesting2" "interesting3".
I am looking for something that scans this folder, this working directory, and check the files by their column names so i can read in the file "interesting.csv" with read_csv2. I would like to know how it's done, because sometimes the file name would change. Let's say "interesting.csv" becomes "interesting_cool.csv", the column names wouldn't change, though. In this case read_csv2("interesting.csv") wouldn't work, because there wouldn't be such a file.
Is there a function, that "scans" all the files in the folder for their headers and compare it to the names i supply to the Rscript?
Something like this: read_csv2(find_file_with_headers("interesting1", "interesting2", "interesting3"))
I am sorry if this is a duplicate, i couldn't find what i need, though.
Regards.
Update to Ronan's approach:
file_list1 <- list.files(getwd(), full.names = TRUE, pattern = "\\.csv$")
file_list2 <- list.files(getwd(), full.names = TRUE, pattern = "\\.CSV$")
(file_list <- c(file_list1, file_list2)); rm(file_list1, file_list2)
col_names = c("interesting1" "interesting2" "interesting3")
file_index <- which(sapply(file_list, function(x)
all(col_names %in% names(read.csv2(x, nrows = 0)))))[1]
return(read.csv2(file_list[file_index]))
If i split it up like this, file_index works fine while "file_index" will result in one NA. If the headers fit, this shouldn't happen, right? Therefor return wouldn't work either and give out the error: Error in file(file, "rt") : invalid 'description' argument