I have multiple .csv files in a folder that I would like to combine into multiple dataframes. I already can do this for one set of files using the following code:
DF_week1 <- list.files(path = 'x:/full/file/path',
pattern = "^Dai15E_ABC_10mbin_20211201_fullwatercolumn_evening_BNR*.*_week1.csv", full.names = TRUE) %>%
map_dfr(read_csv)
I have standard file names like this for about 5 weeks worth of data. What I want to do is make a loop. For example, the first batch of file names ends in "week1" with the next set ending in "week2". I'm trying to write something that would recognize that the number after "week" has changed and to now combine those .csv files into a new data frame (DF_week2, DF_week3, etc.). I'm unfortunately a bit stuck here and rather new to looping.
CodePudding user response:
You can store the dataframes in a list after reading them, and set up a simple for loop:
n = 10 # fill with number of weeks
file_list = list()
for (i in seq(n)) {
file_list[[i]] <- list.files(path = 'x:/full/file/path',
pattern = str_c("^Dai15E_ABC_10mbin_20211201_fullwatercolumn_evening_BNR*.*_week", i, ".csv"), full.names = TRUE) %>%
map_dfr(read_csv)
}