JForsythe
JForsythe

Reputation: 760

R - Importing multiple xlsx files with a for loop

I'm having some trouble writing a function to read in multiple .xlsx files as separate data frames in R with a for loop. When I run the function nothing happens. No Errors, but no data frames are loaded into R either. When I take the assign piece out of the function and manually change the input from the for loop to an example the assign function works. Here is an example of the code:

library(readxl)
Load<-function(File_Path,Samp){
  setwd(File_Path)
  for (i in 1:length(Samp)){
    assign(paste("Sample_",Samp[i],sep = ""),read_excel(paste("Sample_",Samp[i],".xlsx",sep = "")))
  }
}
Load(File_Path = "~/Desktop/Test",Samp = "A") # Doesn't Work

#When this piece is taken out of the loop and the Sample ("A") replaced it works.
assign(paste("Sample_","A",sep = ""),read_excel(paste("Sample_","A",".xlsx",sep = ""))) # Does Work

In reality there is a long list of samples to load and want to do so by assigning a list to "Samp" such as c("A","C","D"). Thanks up front for any assistance.

Upvotes: 0

Views: 181

Answers (1)

Carl
Carl

Reputation: 5779

You can fix your problem by adding inherits=TRUE to assign

Upvotes: 1

Related Questions