R: load data from a folder with multiple files
I have a folder with several files to download:
Each file is a list. And I want to combine all the lists loaded into one list. I am using the following code (the variable loaded each time from the file is called TotalData
):
Filenames <- paste0('DATA3_',as.character(1:18))
Data <- list()
for (ii in Filenames){
load(ii)
Data <- append(Data,TotalData)
}
Is there a more elegant way to write it? For example, using the apply functions?
source to share
You can use lapply
. I am assuming your files were saved with save
, because you are using load
to retrieve them. I am creating two files to use in my example like this:
TotalData<-list(1:10)
save(TotalData,file="DATA3_1")
TotalData<-list(11:20)
save(TotalData,file="DATA3_2")
And then I read them
Filenames <- paste0('DATA3_',as.character(1:2))
Data <- lapply(Filenames,function(fn) {
load(fn)
return (TotalData)
})
After that, it Data
will be a list that contains lists of files as its elements. Since you are using append in your example, I am assuming that this is not what you want. I am removing one level of nesting with
Data <- unlist(Data,recursive=FALSE)
For my two example files, this gave the same output as your code. Whether this is more elegant is debatable, but I would say it is more R-ish than for-loop.
source to share