0

I am trying to create objects from all files in working directory with name of the original file. I tried to go the following way, but couldn't solve appearing problems.

# - SETTING WD
getwd()
setwd("PATH TO THE FILE")
library(readxl)

# - CREATING OBJECTS
file_objects <- list.files()
xlsx_objects <- unlist(grep(".xlsx",file_objects,value = T))

for (i in xlsx_objects) {
  xlsx_objects[i] <- read_xlsx(xlsx_objects[i], header = T)
}

I tried to paste [i]item from "xlsx_objects" with path to WD but it only created a list of files names from docs in WD. I also find information, that read.csv can read only one file at the time, but I guess that it should be the case with for loop, right? It is reading only one file at the time.

Using lapply (as described in this forum) I was able to get the data in the environment, but argument header didn't work, I lost names of my docs in that object which does not have desired structure. I am though looking for having these files in separated objects without calling every document exclusively.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Boris
  • 1
  • 1

1 Answers1

1

IIUC, you could do something like:

files = list.files("PATH TO THE FILE", full.names = T, pattern = 'xlsx')
list_files = map(files, readxl::read_excel)

(You can't use read.csv to read excel files)

Also I recommend reading about R Projects so you don't have to use setwd() ever again, which makes your code harder to reproduce down the pipeline

Juan C
  • 5,846
  • 2
  • 17
  • 51