for loop to load multiple RData files

1.1k views Asked by At

I am new to R. I am trying to load multiple RData files from a single folder using a for-loop, however my below code only loads the last iteration. I am struggling to understand the issue, any solutions or guidance would be greatly appreciated.

myfiles <- list.files("Data/","*.RData", full.names="TRUE")
for (i in 1:length(myfiles)) {
   load(myfiles[i])
}
1

There are 1 answers

0
teej On

The data frame objects in each file were of the same name so it was getting replaced with each iteration.

I was using R script to load the data frames from each file into Power Bi. To do this I had to assign a different name to the data frame object on each iteration. The following solution uses the load.RData function to easily achieve this.

library(miceadds)
myfiles = list.files("Data/","*.RData", full.names="TRUE")
j <- 1
for (i in 1:length(myfiles)){
  load.Rdata(myfiles[i], "df")
  assign(paste("df", j, sep= ""),df)
  j = j+1
  load(myfiles[i])
}
rm(df)