Create multiple data frames from multiple excel files

Hello fellow useRs.

I need your help.

I have multiple excel files stored in a folder.
I want to create a for loop that will read through the files and create different data frames.
What I mean is that, for each excel file that it reads, it generates 1 data frame in R.

So far this is what I have


max_length <- list.files(path = 'Data/raw_data/',
                         pattern = "*.xlsx",
                         full.names = T) %>% length

listofdfs <- data.frame()

for(i in 1:max_length){
  
  name[i] <- list.files(path = 'Data/raw_data/',
           pattern = "*.xlsx",
           full.names = T)[i]
  
   df[i] <- read_excel(name[i])

}

}

But it is not working at all....
I already tried a couple of things but with no luck.

If you also have another suggestion on how to do this, feel free to share.

Instead of a loop, you can do something like this

library(purrr)
library(readxl)

files_list <- list.files(path = 'Data/raw_data/',
                         pattern = "*.xlsx",
                         full.names = TRUE)
files_list %>% 
    walk2(1:length(files_list),
          ~ assign(paste0("df_", .y), 
                   read_excel(path = .x),
                   envir = globalenv()
                   )
          )
1 Like

The more I know about R, the more I realise that I have to learn.
Gracias amigo!

Btw, is there a way to replace the "df" with the name of the files?

lapply method that names the list objects using the file names. I tested this with CSVs but should work fine with any other file type.


my_files <- list.files(YOUR PATH HERE, pattern='.csv', full.names=TRUE)

my_dfs <- lapply(my_files, read.csv)
names(my_dfs) <- my_files
1 Like

I can't test the code but it would be something like this

library(purrr)
library(readxl)
library(stringr)

files_list <- list.files(path = 'Data/raw_data/',
                         pattern = "*.xlsx",
                         full.names = TRUE)
files_list %>% 
    walk(~ assign(str_extract(.x, "(?<=//).+(?=\\.xlsx)"), 
                   read_excel(path = .x),
                   envir = globalenv()
          )
    )
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.