[R] save and load in R

Duncan Murdoch murdoch.duncan at gmail.com
Sun Jun 19 16:38:33 CEST 2011


On 11-06-19 10:26 AM, Mary Kindall wrote:
> I have a list of txt files that I want to convert into .rdata R data
> object.
>
> filenames
> 1. "./file1.txt"
> 2. "./file2.txt"
> 3. "./file3.txt"
> 4. "./file4.txt"
> 5. "./file5.txt"
> 6. "./file6.txt"
> 7. "./file7.txt"
> 8. "./file8.txt"
> 9. "./file9.txt"
> 10. "./file10.txt"
>
> I saved these files as
>
> for ( i in 1:10)
> {
> dataFile = read.table(filenames[i], header=TRUE, sep='\t');
> save (dataFile, file = outfilenames[i])
> }
>
> The inpt files are saves as:
> outfilenames
> 1. "./file1.Rdata"
> 2. "./file2.Rdata"
> 3. "./file3.Rdata"
> 4. "./file4.Rdata"
> 5. "./file5.Rdata"
> 6. "./file6.Rdata"
> 7. "./file7.Rdata"
> 8. "./file8.Rdata"
> 9. "./file9.Rdata"
> 10. "./file10.Rdata"
>
>
> Now I want to load these out files in such a way that the data is loaded
> into a variable that is same as the file name without extension.
>
> file1 = load (file = './file1.Rdata')
> file2 = load (file = './file2.Rdata')
> file3 = load (file = './file3.Rdata')
> file4 = load (file = './file4.Rdata')
>
> How can I do that.

When you load() a file, the variables in it are restored with the same 
names that were saved.  So you would need something like

newnames <- paste("file", 1:10, sep="") # file1, file2, etc.

for (i in 1:10) {
   load(file=outfilenames[i]) # assuming that's still around...
   assign(newnames[i], dataFile)
}

It would be a little simpler to use saveRDS() and readRDS() to save and 
load your files.  They don't save the object names.

A more R-like version of this would be to create a list of datasets, e.g.

files <- list()
for (i in 1:10) {
   load(file=outfilesnames[i])
   files[[i]] <- dataFile
}

Then you don't end up creating 10 objects, but you can still access them 
separately.

Duncan Murdoch



More information about the R-help mailing list