UCLA Academic Technology Services HomeServicesClassesContactJobs
Help the Stat Consulting Group by giving a gift             
Loading

R Code Fragments
How can I write out multiple files with different filenames in R?

If you are creating multiple datasets in R and wish to write them out under different names, you can do so by looping through your data and using the gsub command to generate enumerated filenames. 

The code below presents an example.  A matrix is generated containing seven columns of data. We then loop through the columns of the matrix and write each out as a different file.  To name the files, we create a string called "myfile" where we concatenate a path, a date string, an index that changes as we loop through the columns, and the file extension.  This string contains no spaces and is passed to the write.table command as the name of the output file. 


n<- 7
m<-5
total<-m*n
mymat<-format(matrix(rnorm(total), nrow=m, ncol=n), nsmall =1, digits=2)
mymat
     [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]     
[1,] "-0.3818" " 0.5939" "-0.3264" "-0.3730" "-1.0548" " 0.7681" "-0.3881"
[2,] " 1.0615" "-0.4285" "-1.5244" " 0.4343" " 0.0050" " 1.8232" "-0.6379"
[3,] "-0.0724" " 0.4410" " 0.2003" "-1.6565" " 0.5057" " 1.1976" " 0.4964"
[4,] "-0.1853" " 0.0024" "-0.0155" " 0.1757" "-1.6813" " 0.0164" "-1.2455"
[5,] " 0.8870" "-1.5517" "-1.2553" "-0.6721" " 0.3025" "-0.3071" " 0.2846"

#output n individual data sets, containing a single column
for (i in 1:n) {
  a<-data.frame(mymat[,i])

  mytime<-format(Sys.time(), "%b_%d_%H_%M_%S_%Y") 
  myfile<-gsub("( )", "", paste("c:/temp/", mytime, "_", i, ".txt"))
  
  write.table(a, file=myfile,
                 sep="", row.names=F, col.names=F, quote=FALSE, append=FALSE) 
}

If we are running this code on February 3, 2009, then we have a total of seven files written to the folder c:/temp with names "Feb_03_09_41_01_2009_1.txt" through "Feb_03_09_41_01_2009_7.txt".


How to cite this page

Report an error on this page or leave a comment

UCLA Researchers are invited to our Statistical Consulting Services
We recommend others to our list of Other Resources for Statistical Computing Help
These pages are Copyrighted (c) by UCLA Academic Technology Services


The content of this web site should not be construed as an endorsement of any particular web site, book, or software product by the University of California