Version info: Code for this page was tested in R Under development (unstable) (2012-07-05 r59734)
On: 2012-08-08
With: knitr 0.6.3
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.
set.seed(10) (mymat <- format(matrix(rnorm(5 * 7), nrow = 5, ncol = 7), nsmall = 1, digits = 2))
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] ## [1,] " 0.019" " 0.390" " 1.102" " 0.089" "-0.596" "-0.374" "-1.854" ## [2,] "-0.184" "-1.208" " 0.756" "-0.955" "-2.185" "-0.688" "-0.078" ## [3,] "-1.371" "-0.364" "-0.238" "-0.195" "-0.675" "-0.872" " 0.969" ## [4,] "-0.599" "-1.627" " 0.987" " 0.926" "-2.119" "-0.102" " 0.185" ## [5,] " 0.295" "-0.256" " 0.741" " 0.483" "-1.265" "-0.254" "-1.380"
# output n individual data sets, containing a single column for (i in 1:ncol(mymat)) { a <- data.frame(mymat[, i]) mytime <- format(Sys.time(), "%b_%d_%H_%M_%S_%Y") myfile <- file.path(tempdir(), paste0(mytime, "_", i, ".txt")) write.table(a, file = myfile, sep = "", row.names = FALSE, col.names = FALSE, quote = FALSE, append = FALSE) }
If we are running this code on February 3, 2009, then we have a total of seven files written to Rs temporary directory with names “Feb_03_09_41_01_2009_1.txt” through “Feb_03_09_41_01_2009_7.txt”. You could of course change tempdir() to some other directory, just by changing “tempdir()” for “/path/to/your/directory/”.