'Uploading, reading and naming multiple files from a Network directory in R
I am trying to read several .xlsx files from a network directory that has this path:
\\181.01.2\Global_Office_Net\Accounting
Inside this folder there are several other folders (around 15) and in each of these folders are several files but each folder does have a .xlsx file with a name that starts with "overall_counts_123" the "123" could be any number but the name of the files will always start with "overall_counts" and my goal is to have all files uploaded to Rstudio and rename them with the tag "file1", "file2" etc, I apologize if I'm not being clear let me set an example:
If there are 3 folders in the directory and each folder has "n" files that start with "overall_counts" I would like to get only something like this:
\\181.01.2\Global_Office_Net\Accounting\folder1\overall_counts1.xlsx
\\181.01.2\Global_Office_Net\Accounting\folder2\overall_counts1.xlsx
\\181.01.2\Global_Office_Net\Accounting\folder2\overall_counts15.xlsx
\\181.01.2\Global_Office_Net\Accounting\folder3\overall_counts1008.xlsx
I'm using this code:
file_paths<-fs::dir_ls("\\181.01.2\Global_Office_Net\Accounting")
FILES<-file_paths %>%
map(function(path){
read_xlsx(path)})
But instead of looking in each folder for the files that start with "overall_counts" this is uploading everything and somehow making a list of them... when what I really looking for is to have each desired file uploaded as file2, file2 and so on in separates dataframes I will be so thankful if you could please reference an article on how to upload files based in a criteria for the name of the file and upload them separately thank you so much guys I truly owe you this one
Solution 1:[1]
You can try this:
Get a list of the files that match, looking in all the subfolders (recursive = TRUE)
filenames <- list.files(path = "\\\\181.01.2\\Global_Office_Net\\Accounting\\",
pattern = "overall_counts[0-9]+\\.xlsx",
recursive = TRUE)
Tag with "file1", "file2", etc.
fns <- setNames(filenames, paste0("file", 1:length(filenames)))
Now read these files into R:
library(readxl)
dfs <- lapply(fns, read_xlsx)
This results in a list of dataframes (tibbles) like so: dfs$file1, dfs$file2, etc.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
