Looping importing files with read_xlsx

Hi,

Is there a way to loop this process?

fl123 <- read_xlsx("4-9-fl123.xlsx")
fl121 <- read_xlsx("4-9-fl121.xlsx")
il071 <- read_xlsx("4-9-il071.xlsx")
il082 <- read_xlsx("4-9-il082.xlsx")
il088 <- read_xlsx("4-9-il088.xlsx")
in048 <- read_xlsx("4-9-in048.xlsx")
mo046 <- read_xlsx("4-9-mo046.xlsx")

You can do something like this

library(tidyverse)

list_of_files <- list.files(path = "your_path",
                            pattern = ".xlsx$")
df <- list_of_files %>%
  setNames(nm = .) %>% 
  map_df(read_xlsx, .id = "file_name") 
4 Likes

Is this not already happening? it should be a column named "file_name" containing the name of the datasets, could you share a sample of the output? head(df)

1 Like

Yes, I am sorry, the rest of my code was deleting the column.
Thank you for your help

This thread is already solved, but I'd like to add to Andres answer that in case you want to assign the file contents to separate data.frame's, you can use the assign function. Then, you'll use something like following:

# listing files
xlsx_file_lists <- list.files(pattern = ".xlsx") # if files are in working directory, otherwise add path

# looping and assigning
for (counter in xlsx_file_lists)
{
  assign(x = strsplit(x = counter,
                      split = "[-.]")[[1]][3], # for the pattern in your filenames
         value = readxl::read_xlsx(file = counter))
}
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.